R:使用缩放填充手册更改ggplot填充颜色的问题

R:使用缩放填充手册更改ggplot填充颜色的问题,r,ggplot2,R,Ggplot2,按照R()的食谱,我尝试使用scale_fill_手册在ggplot中更改绘图中点和线的图例和颜色,但它似乎不起作用,几何图形点保持黑色,几何图形平滑保持蓝色。以下是可复制代码: 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

按照R()的食谱,我尝试使用scale_fill_手册在ggplot中更改绘图中点和线的图例和颜色,但它似乎不起作用,几何图形点保持黑色,几何图形平滑保持蓝色。以下是可复制代码:

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

type一般来说,我建议在绘图之前重新映射变量,因为这样可以更容易地编写代码(意味着您可以先检查数据中的值):

注意:线和点使用
颜色
而不是
填充
,并且您只需要
缩放手册
的命名向量参数

如果您的级别的语法不是
name
s,则需要用双引号将其括起来(例如
“非标准”


另请参见。

一般来说,我建议在打印之前重新映射变量,因为这样可以简化代码(意味着您可以先检查数据中的值):

注意:线和点使用
颜色
而不是
填充
,并且您只需要
缩放手册
的命名向量参数

如果您的级别的语法不是
name
s,则需要用双引号将其括起来(例如
“非标准”


另请参见。

谢谢,@Nick Kennedy。这对我来说不太管用…如果我用你的线代替我使用的scale\u fill\u手动线,点的颜色仍然是黑色,线的颜色仍然是蓝色,现在我也失去了所有变量/图例的重命名。也许我把你的代码放错地方了?@RSS对不起,我回答得有点太快了。我在上面做了一些更正,明白了。谢谢你,尼克!谢谢,尼克·肯尼迪。这对我来说不太管用…如果我用你的线代替我使用的scale\u fill\u手动线,点的颜色仍然是黑色,线的颜色仍然是蓝色,现在我也失去了所有变量/图例的重命名。也许我把你的代码放错地方了?@RSS对不起,我回答得有点太快了。我在上面做了一些更正,明白了。谢谢你,尼克!
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")
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")