簡體   English   中英

ggplot圖例:geom_abline干擾

[英]ggplot legend: geom_abline interference

目標:為geom_point一個顏色圖例,為每個組顯示一個彩色的點,為geom_abline一個圖例,為每行顯示一個彩色的線。

難道我做錯了什么? 有解決方案嗎?

# data: mtcars + some made-up straight lines
library(ggplot2)
df = data.frame(Intercept = c(2,3,4), Slope = c(0,0,0), Group = factor(c(1, 2, 3)))

關於#1的評論 :基本圖沒有什么特別的,但是我已經將數據分組到aes() ,並將顏色設置為aes() 我認為在aes中同時具有“分組”和“顏色”以實現分組和着色是標准的。

# 1. my basic plot
ggplot(data = mtcars, aes(x = mpg, y = wt, group = vs, color = factor(vs))) + 
    geom_point() -> p

關於#2的評論 :顯然,我沒有正確設置ggplot正確處理圖例。 我還嘗試在es中添加group = Group 但是還有一個更嚴重的問題: geom_point形成2組,geom_abline形成3組,但是圖例僅顯示4種顏色/線條組合。 其中之一已被合並(綠色的)。 我在這里做錯了什么?

# 2. my naive attempt to add ablines of 3 different colours
p + geom_abline(data = df, aes(intercept = Intercept, slope = Slope,
                           colour = Group))

在此處輸入圖片說明

關於#3的評論 :圖例中的縮寫已被刪除,但要點仍然不正確。 從這里開始,它變得越來越絕望。

# 3. Suppress the ab_line legend?
p + geom_abline(data = df, aes(intercept = Intercept, slope = Slope,
                           colour = Group), show.legend = FALSE)

在此處輸入圖片說明

關於#4的評論 :這就是我目前要去的地方。 沒有傳說總比錯誤的傳說更好。 可惜丟掉顏色。

# 4. Remove the geom_abline legend AND colors
p + geom_abline(data = df, aes(intercept = Intercept, slope = Slope))

在此處輸入圖片說明

注釋#5 :我不知道我在這里希望什么...如果我在geom_point()而不是ggplot()的調用內定義數據和aes, geom_abline())不會以某種方式劫持顏色和傳說,但沒有,它似乎沒有什么不同。

# 5. An attempt to set the aes inside geom_point() instead of ggplot()
ggplot() + 
    geom_point(data = mtcars, aes(x = mpg, y = wt, group = vs, color = factor(vs))) + 
    geom_abline(data = df, aes(intercept = Intercept, slope = Slope, color = "groups")) +
    scale_color_manual(values = c("red", "blue", "black"))

在此處輸入圖片說明

一種選擇是對mtcars數據使用填充形狀,然后可以有一個fill比例和一個colour標,而不是兩個colour標。 如果不想使用黑色輪廓線,可以在geom_point語句中添加諸如colour="white"類的選項,以更改點邊緣的顏色。

library(ggplot2)
df = data.frame(Intercept = c(2,3,4), Slope = c(0,0,0), Group = factor(c(1, 2, 3)))
ggplot(data = mtcars, aes(x = mpg, y = wt, group = vs, fill = factor(vs))) + 
           geom_point(shape=21, size=2) +
           geom_abline(data = df, aes(intercept = Intercept, slope = Slope,
                              colour = Group))

在此處輸入圖片說明

如果您需要或想要圖例中有一條水平線,則可以考慮使用以下代碼:

library(ggplot2)
df = data.frame(Intercept = c(2,3,4), Slope = c(0,0,0),
Group = factor(c(1, 2, 3)))
ggplot(data = mtcars,
   aes(x = mpg, y = wt, group = vs, fill = factor(vs))) + 
geom_point(shape=21, size=2) +
geom_hline(data = df,
          aes(yintercept = Intercept,colour = Group))

用geom_hline繪圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM