如何在 ggplot 中手动添加颜色并在同一图中重命名图例标签?

M.R*_*ani 4 r ggplot2

p <- ggplot(mpg, aes(x= displ, y= hwy, fill = drv)) + 
  geom_bar(stat = "identity") + 
  scale_fill_manual(values = c("forestgreen", "blue", "deepred"))
Run Code Online (Sandbox Code Playgroud)

当我添加以下代码来更改图例标签时:

p + scale_fill_discrete(labels = c("4wd", "front", " rear"))
Run Code Online (Sandbox Code Playgroud)

我收到此错误警告:

“填充”的比例已经存在。添加另一个比例“填充”,这将取代现有比例。

因此它会替换现有的比例并返回到第一个比例。如何预防?

Cla*_*lke 5

您需要同时提供值和标签。

library(ggplot2)
ggplot(mpg, aes(x= displ, y= hwy, fill = drv)) + 
  geom_bar(stat = "identity") + 
  scale_fill_manual(
    values = c("forestgreen", "blue", "darkred"),
    labels = c("4wd", "front", " rear")
  )
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因你有一个带有比例的图并且想要更新比例,那也很好,但是你再次需要一次设置你需要的所有参数。

library(ggplot2)
p <- ggplot(mpg, aes(x= displ, y= hwy, fill = drv)) + 
  geom_bar(stat = "identity") + 
  scale_fill_manual(
    values = c("forestgreen", "blue", "darkred")
  )

p + scale_fill_manual(
  values = c("forestgreen", "blue", "darkred"),
  labels = c("4wd", "front", " rear")
)
#> Scale for 'fill' is already present. Adding another scale for 'fill',
#> which will replace the existing scale.
Run Code Online (Sandbox Code Playgroud)