繁体   English   中英

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

[英]R: Issues changing ggplot fill colors with scale_fill_manual

继Cookbook for R( http://www.cookbook-r.com/Graphs/Legends_ (ggplot2 )之后,我试图使用scale_fill_manual在ggplot中更改点和线的图例和颜色,但是它似乎没有工作 - geom_points保持黑色,并且geom_smooths保持蓝色。 这是可重现的代码:

type <- c("0", "0", "1", "2", "2", "2", "2", "1")
votes <- c(21, 28, 52, 66, 65, 42, 48, 39)
time <- c(1, 2, 3, 4, 5, 6, 7, 8)
df <- data.frame(type, votes, time)

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

我试图将标有“标准”的点和线显示为深蓝色,“非标准”点和线显示深紫色,“Oddball”点和线显示深红色,但所有点都显示黑色和线条都显示蓝色:

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

任何人都有修复? 先感谢您!

通常,我建议在绘图之前重新映射变量,因为它使代码更容易(并且意味着您可以先检查数据中的值):

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")

但是,否则,您只需将美学更改为colour而不是fill

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")

情节

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

如果您的级别不是name的语法,则需要用双引号括起来(例如"Non-standard" )。

另请参见手册

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM