R:使用scale_fill_manual更改ggplot填充颜色的问题

RSS*_*RSS 1 r ggplot2

遵循 R 食谱 ( http://www.cookbook-r.com/Graphs/Legends_(ggplot2)),我尝试使用scale_fill_manual更改ggplot中绘图中点和线的图例和颜色,但它似乎不起作用\xe2\x80\x94geom_points 保持黑色,geom_smooths 保持蓝色。这是可重现的代码:

\n\n
type <- c("0", "0", "1", "2", "2", "2", "2", "1")\nvotes <- c(21, 28, 52, 66, 65, 42, 48, 39)\ntime <- c(1, 2, 3, 4, 5, 6, 7, 8)\ndf <- data.frame(type, votes, time)\n\ntest.plot <- ggplot(df, aes(y = votes, x = time, fill = type)) +\ngeom_point() +\ngeom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) +\nscale_fill_manual(values=c("blue4", "purple4", "red4"),\n                breaks=c("2","1","0"),\n                labels=c("Standard", "Nonstandard", "Oddball"),\n                name="Type")\ntest.plot\n
Run Code Online (Sandbox Code Playgroud)\n\n

我试图让标记为“标准”的点和线显示为深蓝色,“非标准”点和线显示为深紫色,“奇怪”的点和线显示为深红色,但所有点都显示黑色,线条全部显示蓝色:

\n\n

https://i.stack.imgur.com/IylCg.jpg

\n\n

有人有解决办法吗?先感谢您!

\n

Nic*_*edy 5

一般来说,我建议在绘图之前重新映射变量,因为它可以使代码更简单(并且意味着您可以首先检查数据中的值):

df$type <- factor(df$type, levels = 0:2,
                  labels = c("Oddball", "Nonstandard", "Standard"))

test.plot <- ggplot(df, aes(y = votes, x = time, colour = type)) +
  geom_point() +
  geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) +
  scale_colour_manual(values=c("Standard" = "blue4", "Nonstandard" = "purple4",
    "Oddball" = "red4"), name="Type")
Run Code Online (Sandbox Code Playgroud)

但是,否则,您只需将美观更改colourfill

test.plot <- ggplot(df, aes(y = votes, x = time, colour = type)) +
  geom_point() +
  geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) +
  scale_colour_manual(values=c("blue4", "purple4", "red4"),
                    breaks=c("2","1","0"),
                    labels=c("Standard", "Nonstandard", "Oddball"),
                    name="Type")
Run Code Online (Sandbox Code Playgroud)

阴谋

请注意,线和点使用colour而不是,fill并且您只需要 的命名向量参数scale_x_manual

如果您的级别在语法上与 s 不同name,则需要用双引号将它们引起来(例如"Non-standard")。

另请参阅手册