ggplot2 的 geom_line 中线条的不同大小

MER*_*ose 3 r ggplot2 line-plot

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

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

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

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

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
Run Code Online (Sandbox Code Playgroud)

有趣的是,geom_line(..., size=cut)可以工作,但不符合预期,因为它根本不会改变线条大小。

Lyz*_*deR 5

为此,您需要创建一个新变量,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)
Run Code Online (Sandbox Code Playgroud)

请注意,上面的内容可以使用以下代码替换dplyr

diamonds %>% group_by(cut) %>% mutate(size = length(cut) / nrow(diamonds))
Run Code Online (Sandbox Code Playgroud)

然后,您需要遵循@Heroka的建议,并aes在diams data.frame中使用新创建的列的内部尺寸:

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

它有效:

在此输入图像描述