簡體   English   中英

在ggplot中添加手動圖例

[英]Adding manual legend in ggplot

我已經瀏覽了之前的類似問題,並且(我認為)已經完成了其中推薦的所有內容。 仍然沒有得到我想要的輸出。

我有一堆分布,我將它們顯示在分面圖中。 然后我通過它們畫垂直線,代表不同的干預措施。

我正在嘗試顯示一個圖例,其中包含分布的填充顏色以及這些額外線條的線條顏色。 據我所知,我做的一切都是正確的(在aes()設置顏色命令,使用scale_colour_manual()來定義圖例等)。 我仍然只得到填充顏色的圖例。

這是我的代碼:

ggplot(modCosts, aes(x=cost)) + geom_density(aes(fill=group)) + theme_bw() +
  facet_wrap(~ country, scales="free") + scale_x_continuous(label = dollar) +
  scale_fill_brewer(palette = "RdGy", name = "Income group", labels = c("HIC" = "High income", "UMIC" = "Upper-middle income", "LIC" = "Low income")) + 
  labs(y = "Density", x = "Cost", title = "Medical costs of surgery\nActual vs. modeled") + 
  geom_vline(data = surgCosts, aes(xintercept = CS.tert.lo, color = "red4")) +
  geom_vline(data = surgCosts, aes(xintercept = CS.tert.hi, color = "red4")) + 
  geom_vline(data = surgCosts, aes(xintercept = CS.prim.lo, color = "red4"), lty = "dashed") + 
  geom_vline(data = surgCosts, aes(xintercept = CS.prim.hi, color = "red4"), lty = "dashed") + 
  geom_vline(data = surgCosts, aes(xintercept = Lap.tert.lo, color = "deepskyblue")) +
  geom_vline(data = surgCosts, aes(xintercept = Lap.tert.hi, color = "deepskyblue")) + 
  geom_vline(data = surgCosts, aes(xintercept = Lap.prim.lo, color = "deepskyblue"), lty = "dashed") + 
  geom_vline(data = surgCosts, aes(xintercept = Lap.prim.hi, color = "deepskyblue"), lty = "dashed") + 
  geom_vline(data = surgCosts, aes(xintercept = Fx.tert.lo, color = "yellowgreen")) + 
  geom_vline(data = surgCosts, aes(xintercept = Fx.tert.hi, color = "yellowgreen")) + 
  scale_color_manual(name = "Reported cost", values = c("red4" = "red4", "deepskyblue" = "deepskyblue", "yellowgreen" = "yellowgreen"),
                      labels = c("Int1", "Int2", "Int3")) +
  theme(axis.ticks = element_blank(), axis.text.y = element_blank(), legend.position = "right") 

這是我得到的輸出: 在此處輸入圖片說明

任何幫助將不勝感激!

geom_vline(...) (以及_hline_abline )有一個show_guide=...參數,默認為FALSE 顯然,大多數情況下,您不希望線條顏色顯示在圖例中。 這是一個例子。

df <- mtcars
library(ggplot2)
ggp <- ggplot(df, aes(x=wt, y=mpg, fill=factor(cyl))) +
  geom_point(shape=21, size=5)+
  geom_vline(data=data.frame(x=3),aes(xintercept=x, color="red"), show_guide=TRUE)+
  geom_vline(data=data.frame(x=4),aes(xintercept=x, color="green"), show_guide=TRUE)+
  geom_vline(data=data.frame(x=5),aes(xintercept=x, color="blue"), show_guide=TRUE)

ggp +scale_color_manual("Line.Color", values=c(red="red",green="green",blue="blue"),
                     labels=paste0("Int",1:3))

順便說一句,如果您堅持使用顏色名稱,則指定比例的更好方法是:

ggp +scale_color_identity("Line.Color", labels=paste0("Int",1:3), guide="legend")

產生上面相同的圖。

暫無
暫無

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

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