Ggplot2:更改单个值的颜色

时间:2018-12-13 17:21:50

标签: r ggplot2

我正在尝试使用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 个答案:

答案 0 :(得分: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