首页 文章

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

提问于
浏览
1

按照R的Cookbook(http://www.cookbook-r.com/Graphs/Legends_(ggplot2)),我似乎正在工作 - 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

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

1 回答

  • 3

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

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

    Plot

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

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

    另见manual .

相关问题