繁体   English   中英

ggplot2的geom_line中线的大小不同

[英]Different size for lines in ggplot2's geom_line

是否可以用geom_line绘制不同尺寸(即粗线)的线?

所有行的大小参数均相同,与组无关:

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

但是,我希望这些线的粗细能够反映其相对重要性,以观察次数来衡量:

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

有趣的是, geom_line(..., size=cut)可以正常工作,但是却没有达到预期效果,因为它根本不会改变线的大小。

为此,您需要为relative_size创建一个新变量,该变量的长度将与data.frame的行相同,并将其添加到data.frame中。 为此,您可以执行以下操作:

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

请注意,可以使用dplyr将以上内容替换为代码:

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

然后,您需要遵循@Heroka的建议,并在diams data.frame中将新创建的列与aes一起使用size:

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

它的工作原理是:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM