ggplot2:更改单个值的颜色

3
我正在尝试使用ggplot创建一条线图,并且我想将一个值的颜色设置为黑色,其余默认。我需要使用这个代码创建多个线图,而仅值(这里是“ A”)在所有图中保持不变。
我的问题是: 我设法解决了它,但现在我的问题是该值不再与其他值一起显示在图例中。如何使其再次出现在那里?
mydata <- data.frame("Letter" = c("A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D",
"A", "B", "C", "D"), "Month" = c("Jan", "Jan", "Jan", "Jan", "Feb", "Feb", "Feb", "Feb",
"Mar", "Mar", "Mar", "Mar", "Apr", "Apr", "Apr", "Apr"), "Number" = c(1, 2, 3, 4, 4, 5, 1, 3,
6, 4, 2, 4, 1, 2, 5, 7))

这个图表是我想要的,但是“A”在图例中没有显示。

ggplot(data = mydata, aes(x = Month, y = Number, colour = Letter, group = Letter))
+ theme(legend.position="bottom", legend.title = element_blank())
+ geom_line(data=subset(mydata, Letter == "A"), colour="black", size = 1)
+ geom_line(data=subset(mydata, Letter != "A"), size = 1)
+ geom_point(data=subset(mydata, Letter == "A"), colour="black", size = 1.5)
+ geom_point(data=subset(mydata, Letter != "A"), size = 1.5)

在图例中显示“A”,但其线条/点并不是黑色。
ggplot(data = mydata, aes(x = Month, y = Number, colour = Letter, group = Letter))
+ theme(legend.position="bottom", legend.title = element_blank())
+ geom_line()
+ geom_point(size = 1.5)

有人知道如何解决这个问题吗?

1个回答

1
#show the three colors of the ggplot default
library(scales)
show_col(hue_pal()(3))

#set colors
group.colors <- c(A = "#000000", B = "#F8766D", C = "#00BA38", D = "#619CFF" )

#plot
library( ggplot2)
ggplot(data = mydata, aes(x = Month, y = Number, colour = Letter, group = Letter)) + 
  theme(legend.position="bottom", legend.title = element_blank()) +
  geom_line( data = mydata, size = 1 ) + 
  geom_point(data = mydata, size = 1.5 ) +
  scale_colour_manual( values= group.colors )  # <-- set the chosen colors

enter image description here


有没有不需要定义B、C和D颜色的方法来完成它? - Hurlikus
@Hurlikus 我相信你必须手动设置它们...但是你可以使用hue_pal函数来完成...group.colors <- c("#000000", hue_pal()(3)),然后给向量命名names( group.colors ) <- LETTERS[1:4] - Wimpel
您能否给我一个使用上述代码的例子?“names…”部分应该放在哪里? - Hurlikus
@Hurlikus 首先,你使用 scales::hue_pal() 函数创建一个颜色向量。然后,使用 names 为这个向量设置名称... ggplot 在图例中进一步处理。library(scales); group.colors <- c("#000000", hue_pal()(3)); names( group.colors ) <- LETTERS[1:4]; group.colors - Wimpel
谢谢,我会尝试的! - Hurlikus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接