h09812349
h09812349

Reputation: 139

Scale ggplot line size to sample size

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

Upvotes: 1

Views: 471

Answers (2)

Rfanatic
Rfanatic

Reputation: 2282

You can plot the widths proportional to your variables.

Sample code:

  library(ggplot2)

  ggplot(df,aes(x=time, y=pct, group=animal, color=animal)) + 
  geom_line(aes(size = n))+
  labs(x="Time", y="Pct", color="Categories of animals")+
  theme_minimal()

Plot:

enter image description here

Or you can colour the widths proportional to your variables.

ggplot(df,aes(x=time, y=pct, group=animal, color=animal)) + 
  geom_line(aes(color= n), lwd=2)+
  labs(x="Time", y="Pct", color="N")+
  theme_minimal()

Plot: enter image description here

Sample data:

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))

Upvotes: 0

zephryl
zephryl

Reputation: 17079

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()

Upvotes: 3

Related Questions