是否可以使用 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
它有效:
关于r - ggplot2 的 geom_line 中线条的大小不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32823752/