我想創建一個線圖,其中線的粗細與組的樣本大小成正比。例如,在下面的示例資料中,我希望代表狗的紅線比代表豬的藍線粗。我可以在ggplot中做到這一點嗎?
編輯:我希望 ggplot 自動執行此操作,而不必手動調整每行的行大小。
示例代碼:
animal<-c("pig","dog")
pct<-c(51.34,67.85,45.67,59.34,77.85,85.67)
n<-c(100,100,100,900,900,900)
time<-c(1,2,3)
df<-as.data.frame(cbind(animal, pct,n,time))
ggplot(df,aes(x=time, y=pct, group=animal, color=animal)) geom_line(size=1)

uj5u.com熱心網友回復:
您可以簡單地將size美學映射到n. (請注意,我更改了您的示例資料以反映我認為您真正想要的 - 您的示例資料在兩組中具有不同的樣本量,并且n作為字符而不是數字。)
library(ggplot2)
animal<-c("pig", "dog")
pct<-c(51.34,67.85,45.67,59.34,77.85,85.67)
# n<-c(100,100,100,900,900,900)
n<-c(100,900,100,900,100,900)
time<-c(1,2,3)
# `cbind()` will coerce everything to character;
# instead, just use `data.frame()`
# df<-as.data.frame(cbind(animal, pct,n,time))
df <- data.frame(animal, pct,n,time)
ggplot(df,aes(x=time, y=pct, color=animal, size=n, group=animal))
geom_line()
uj5u.com熱心網友回復:
您可以繪制與widths變數的比例。
示例代碼:
library(ggplot2)
ggplot(df,aes(x=time, y=pct, group=animal, color=animal))
geom_line(aes(size = n))
labs(x="Time", y="Pct", color="Categories of animals")
theme_minimal()
陰謀:

或者您可以為與變數成比例的寬度著色。
ggplot(df,aes(x=time, y=pct, group=animal, color=animal))
geom_line(aes(color= n), lwd=2)
labs(x="Time", y="Pct", color="N")
theme_minimal()
陰謀:
樣本資料:
animal<-c("pig","dog")
pct<-c(51.34,67.85,45.67,59.34,77.85,85.67)
n<-c(100,100,100,900,900,900)
time<-c(1,2,3)
df<-as.data.frame(cbind(animal, pct,n,time))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/444196.html
