Home > front end >  Scale ggplot line size to sample size
Scale ggplot line size to sample size

Time:03-15

I would like to create a line plot where the thickness of the line is proportional to the sample size of the group. For example, in the sample data below, I would want the red line representing dog to be thicker than the blue line for pig. Would I be able to do this in ggplot?

Edit: I would like ggplot to do this automatically and not have to manually adjust the line size for each line.

Sample code:


animal<-c("pig","dog")
pct<-c(51.34,67.85,45.67,59.34,77.85,85.67)
n<-c(100,100,100,900,900,900)
time<-c(1,2,3)

df<-as.data.frame(cbind(animal, pct,n,time))

ggplot(df,aes(x=time, y=pct, group=animal, color=animal))   geom_line(size=1)

enter image description here

CodePudding user response:

You can simply map the size aesthetic to n. (Note that I changed your example data to reflect what I think you actually wanted — your example data had differing sample sizes within the two groups, and n as character instead of numeric.)

library(ggplot2)

animal<-c("pig", "dog")
pct<-c(51.34,67.85,45.67,59.34,77.85,85.67)
# n<-c(100,100,100,900,900,900)
n<-c(100,900,100,900,100,900)
time<-c(1,2,3)

# `cbind()` will coerce everything to character;
# instead, just use `data.frame()`
# df<-as.data.frame(cbind(animal, pct,n,time))
df <- data.frame(animal, pct,n,time)

ggplot(df,aes(x=time, y=pct, color=animal, size=n, group=animal))  
  geom_line()
  • Related