[英]Controlling linetype, color and label in ggplot legend
我在先前也已指定自定義線型和顏色的繪圖上設置自定義圖例標簽時遇到麻煩。 在stackoverflow上有一個類似的問題,涉及線型和線色的自定義圖例。 但是,一旦您希望在上述兩個屬性之上指定圖例標簽,ggplot2似乎開始崩潰。
這是我的可重復性最低的示例:
library(ggplot2)
df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
treatment = c(rep("one", 2), rep("two", "2")))
ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
geom_line() +
scale_linetype_manual(values = c(1, 3),
labels = c("Treatment one", "Treatment two")) +
scale_color_manual(values = c("black", "red"))
上面的代碼導致下圖
在scale_linetype_manual()
或scale_color_manual()
設置標簽會導致創建兩個單獨的圖例。 具有正確虛線的那個將永遠是無色的。 另一方面,具有正確顏色的線將不能正確表示線型(僅實線)。
是否可以在ggplot2中同時控制顏色,線型和圖例標簽? 還是這是軟件包的限制,我應該只在getgo的數據框中正確指定標簽?
使scale_linetype_manual()
和scale_color_manual()
的標簽相同。
library(ggplot2)
df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
treatment = c(rep("one", 2), rep("two", "2")))
ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
geom_line() +
scale_linetype_manual(values = c(1, 3),
labels = c("Treatment one", "Treatment two")) +
scale_color_manual(values = c("black", "red"),
labels = c("Treatment one", "Treatment two"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.