将ggplot图例颜色与数据框中的实际颜色相匹配

Matching ggplot legend color with actual color in dataframe

我有一个包含颜色列的数据框。示例数据如下所示:

structure(list(group = c("green", "red", "blue", "green", "red", 
"blue", "green", "red", "blue", "green", "red", "blue", "green", 
"red", "blue", "green", "red", "blue", "green", "red", "blue", 
"green", "red", "blue"), y = c(4.6, 8.3, 4.6, 4.7, 9, 2.6, 9, 
10, 7.5, 6.7, 8.3, 6.2, 6.2, 7.8, 7, 7.7, 9.1, 4.7, 7.5, 7.5, 
8.3, 7.4, 7.6, 5.7), CO = c(3.5, 4.2, 5.9, 3.3, 2.2, 5, 4.4, 
5.5, 5.1, 3.9, 2.1, 4.3, 4.3, 4.5, 5.4, 3.6, 5.8, 4.7, 4.8, 2.9, 
4.8, 4.3, 5.5, 3.4), age = c(18, 19, 25, 18, 22, 18, 29, 19, 
41, 19, 18, 24, 19, 26, 32, 23, 18, 24, 22, 21, 18, 22, 19, 18
), gender = c("Male", "Male", "Male", "Male", "Female", "Female", 
"Female", "Female", "Female", "Female", "Female", "Male", "Male", 
"Male", "Female", "Male", "Female", "Female", "Male", "Female", 
"Male", "Male", "Male", "Female")), row.names = c(NA, -24L), class = c("tbl_df", 
"tbl", "data.frame"))

我想使用“颜色”列对观察结果进行分组并将其绘制在图表上。我写了如下所示的命令:

ggplot(df_long, aes(x=CO, y=y, color=group, shape=group)) +
  geom_point() + 
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE)+
  theme(plot.title = element_text(hjust = 0.5))+theme(
    legend.title = element_text( size = 14),
    legend.text = element_text( size = 10)
  )

结果如下图:

可以看出,图例与实际颜色不符,例如,颜色为“红色”的组显示为“蓝色”。我累了补充

scale_color_manual(breaks = c("red", "blue", "green"),
                 values=c("red", "blue", "green"))

这导致了下图:

首先,与之前的图表相比,颜色并不是很吸引人,它们变成了不同的颜色(不知何故真的很闪亮!这使得图表很难看清)。更重要的是,我现在有 2 个图例,但我不确定如何解决这个问题。有什么建议吗?

使用 scale_shape_discrete() 尝试这种方法。包含您的数据的示例和代码:

library(ggplot2)
#Code
ggplot(df_long, aes(x=CO, y=y, color=group, shape=group)) +
  geom_point() + 
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE)+
  theme(plot.title = element_text(hjust = 0.5))+theme(
    legend.title = element_text( size = 14),
    legend.text = element_text( size = 10)
  )+
  scale_color_identity(guide = 'legend')

输出:

已更新以匹配变量中的颜色。非常感谢 @erc

对于其他颜色试试这个:

#Code2
ggplot(df_long, aes(x=CO, y=y, color=group, shape=group)) +
  geom_point() + 
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE)+
  theme(plot.title = element_text(hjust = 0.5))+theme(
    legend.title = element_text( size = 14),
    legend.text = element_text( size = 10)
  )+
  scale_color_manual(breaks = c("red", "blue", "green"),
                     values=c("tomato", "cyan3", "darkgreen"))+
  scale_shape_discrete(breaks = c("red", "blue", "green"))

输出: