Different size for lines in ggplot2's geom_line

ⅰ亾dé卋堺 提交于 2019-12-12 17:27:10

问题


Is it possible to have different sized (i.e. thick) lines drawn with geom_line?

The size parameters is the same for all lines, irrespective of the group:

bp <- ggplot(data=diamonds, aes(x=cut, y=depth)) +
  geom_line(aes(color=cut), size=1)

However, I want the thickness of the lines to reflect their relative importance measured as number of observations:

relative_size <- table(diamonds$cut)/nrow(diamonds)
bp <- ggplot(data=diamonds, aes(x=cut, y=depth)) +
  geom_line(aes(color=cut), size=cut)
bp
# Error: Incompatible lengths for set aesthetics: size

Interestingly, geom_line(..., size=cut) works but not as expected, since it doesn't alter line size at all.


回答1:


In order to do this you need to create a new variable for relative_size that will be of the same length as the rows of the data.frame and add it to your data.frame. In order to do this, you could do:

#convert relative_size to a data.frame
diams <- diamonds
relative_size <- as.data.frame(table(diamonds$cut)/nrow(diamonds))

#merge it to the diams data.frame so that it has the same length
diams <- merge(diams, relative_size, by.x='cut', by.y='Var1', all.x=TRUE)

Note that the above can be replaced by code using dplyr:

diamonds %>% group_by(cut) %>% mutate(size = length(cut) / nrow(diamonds))

Then you need to follow @Heroka 's advice and use size inside of aes with your newly created column in your diams data.frame:

bp <- ggplot(data=diams, aes(x=cut, y=depth)) +
  geom_line(aes(color=cut, size=Freq))
bp

And it works:



来源:https://stackoverflow.com/questions/32823752/different-size-for-lines-in-ggplot2s-geom-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!