ggplot2的geom_line中线条的大小不同 [英] Different size for lines in ggplot2's geom_line

查看:5816
本文介绍了ggplot2的geom_line中线条的大小不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 geom_line



绘制不同大小的线(即粗线)尺寸参数对于所有行而言,与组无关:

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

然而,我希望线条的粗细能够反映它们相对重要性的测量结果:观察次数:

  relative_size< ;  - 表(钻石$ cut)/ nrow(钻石)
bp < - ggplot(data =钻石,aes(x = cut,y = depth))+
geom_line(aes(color = cut ),size = cut)
bp
#错误:设置美学的长度不兼容:size

有趣的是, geom_line(...,size = cut)可以工作,但并不像预期的那样,因为它根本不会改变行的大小。

解决方案

为了做到这一点,您需要为 relative_size 创建一个新变量。 code>,它的长度与data.frame的行长度相同,并将其添加到data.frame中。为了做到这一点,你可以这样做:

  #convert relative_size to a data.frame 
diams< - 钻石
relative_size< - as.data.frame(表格(钻石$ cut)/ nrow(钻石))

#将它合并到diams data.frame,以便它具有相同的长度
diams< - 合并(diams,relative_size,by.x ='cut',by.y ='Var1',all.x = TRUE)
pre>




注意上面的代码可以用 dplyr

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






然后您需要关注@Heroka在您的diams data.frame中新创建的列的 aes 中的建议和使用大小:



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

它的作用:


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.

解决方案

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:

这篇关于ggplot2的geom_line中线条的大小不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆