簡體   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