簡體   English   中英

僅使用geom_areas更改ggplot2中的圖例顏色

[英]Change the legend coloring in ggplot2 with geom_areas only

我有以下ggplot對象:

ggplot(data.frame(x = c(3, 15)), aes(x)) + 
  geom_area(aes(color = "Gruppe A"), stat = "function", fun = dnorm, args = list(mean = 10, sd = 2), fill = "blue", alpha=.5, xlim = c(3, 15)) +
  geom_area(aes(color = "Gruppe B"), stat = "function", fun = dnorm, args = list(mean = 9, sd = 2), fill = "red", alpha=.5, xlim = c(3, 15)) +
  scale_fill_discrete(name = "Name", labels = c("Gruppe A", "Gruppe B")) +
  scale_color_manual(values=c("Gruppe A"="blue", "Gruppe B"="red")) +
  scale_x_continuous(name = "Note", breaks = c(3:15), limits = c(3, 15)) + 
  scale_y_continuous(name = "Dichte")

我嘗試通過添加scale_color_manual手動添加圖例。 但是,圖例填充顏色與geom_area圖層的顏色不匹配。 如何手動配置此填充顏色?

您很接近,但是您的代碼需要進行一些其他調整:

還指定aes -call內部的fill -color。 然后,您可以使用scale_fill_manual指定填充的顏色。 由於您具有相同的填充顏色和外部邊界,因此可以指定aesthetics = c("color", "fill")來將其應用於兩種美學。

ggplot(data.frame(x = c(3, 15)), aes(x)) + 
  geom_area(aes(color = "Gruppe A", fill = "Gruppe A"), stat = "function", fun = dnorm, args = list(mean = 10, sd = 2), alpha=.5, xlim = c(3, 15)) +
  geom_area(aes(color = "Gruppe B", fill = "Gruppe B"), stat = "function", fun = dnorm, args = list(mean = 9, sd = 2), alpha=.5, xlim = c(3, 15)) +
  scale_fill_manual(name = "Name", values = c("Gruppe A" = "blue", "Gruppe B" = "red"), aesthetics = c("color", "fill")) +
  scale_x_continuous(name = "Note", breaks = c(3:15), limits = c(3, 15)) + 
  scale_y_continuous(name = "Dichte")

在此處輸入圖片說明

暫無
暫無

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

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