3

是否可以绘制不同大小(即粗)的线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)它可以工作,但并不像预期的那样,因为它根本不会改变线的大小。

4

1 回答 1

4

为此,您需要创建一个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在您的 diams data.frame 中使用您新创建的列的大小:

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

它有效:

在此处输入图像描述

于 2015-09-28T13:26:30.110 回答