r - ggplot2 的 geom_line 中线条的大小不同

标签 r ggplot2 line-plot

是否可以使用 geom_line 绘制不同大小(即粗)的线?

无论组如何,所有行的大小参数都相同:

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

但是,我希望线条的粗细能够反射(reflect)它们以观察次数衡量的相对重要性:

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 的建议并在 aes 中使用 size 以及您在 diams data.frame 中新创建的列:

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

它有效:

enter image description here

关于r - ggplot2 的 geom_line 中线条的大小不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32823752/

相关文章:

r - 如何检查 R 是否已经安装在 Ubuntu 中?

从 r 中的列中删除重复的元素

仅当用户选择按钮时渲染绘图

r - 有没有办法向ggmap添加比例尺(用于线性距离)?

r - 在ggplot2中制作带有离散x轴的线图

python - 使用pyplot在python中的多个子图上绘制水平线

r - 保持矩阵列表中每行的 2 个最高值 r

r - 无法在 R Studio 中安装包

r - R : fill underneath a geom_smooth line 中的 ggplot2

python - 如何在线图中放置内联标签