我正在繪制由一個因子分隔的多條回歸線count。
- 我需要所有的線條都是相同的顏色和透明度(例如顏色 = 紅色,alpha = 0.5)
- 為圖中的所有線條畫一個平均值,例如黑色虛線)
我嘗試將顏色 alpha 引數添加到,geom_line()但它產生了一行。有什么建議?

#CODE 生成上圖
count <- c(1,2,3,1,2,3,1,2,3 1,2,3,1,2,3)
xcount <- rnorm(15,3,1)
ycount <- rnorm(15,5,1))
df <- data.frame(count, xcount, ycount)
ggplot(aes(x = xcount, y = ycount, color = factor(count)), data = df)
geom_smooth(method = "lm", fill = NA)
theme(panel.background = element_blank())
ylab("Y")
xlab ("X") theme(legend.position="none")
uj5u.com熱心網友回復:
將您的組美學移出第一個 ggplot 宣告,然后在第一個 geom_smooth 中使用您的分組來創建 3 條紅線。添加另一個沒有分組的 geom_smooth 以在所有值上創建線(平均值)
ggplot(aes(x = xcount, y = ycount), data = df)
geom_smooth(aes(group = factor(count)), method = "lm", fill = NA, color = "red")
geom_smooth(method = "lm", fill = NA, color = "black", linetype = "longdash")
請注意,在上面的alpha = 0.5,因為它是被洗掉不支持的geom_smooth,以實作以及可以使用stat_smooth,而不是像這樣讓你的紅線將有希望的透明度。
ggplot(aes(x = xcount, y = ycount), data = df)
stat_smooth(aes(group = factor(count)), geom = "line", method = "lm", se = FALSE, color = "red", alpha=0.5)
stat_smooth(geom = "line", method = "lm", se = FALSE, color = "black", linetype = "longdash")
uj5u.com熱心網友回復:
對于單一顏色和 alpha,只需將您指定的維度拉到aes()呼叫之外。之外的任何內容aes都將應用于每一行。訣竅還在于指定組以避免獲得單行。
ggplot(aes(x = xcount, y = ycount, group = factor(count), data = df)
geom_smooth(method = "lm", fill = NA, color = 'red', alpha = 0.5)
至于平均線,最簡單的方法是在繪圖之前預先計算平均值。假設您將平均值放在一個名為 的變數中mu,您只需添加以下內容:
geom_hline(yintercept = mu, linetype = 'longdash')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420823.html
標籤:
