gpt4 book ai didi

r - Ggplot2:更改单个值的颜色

转载 作者:行者123 更新时间:2023-12-02 02:47:31 25 4
gpt4 key购买 nike

我正在尝试使用 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)

有人知道怎么解决吗?

最佳答案

#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

关于r - Ggplot2:更改单个值的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53767091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com