我想创建一个具有多个组(〜10)的灰度线图,但其中的线(spec=3)
为红色。
请参见下面仅包含三个组的示例:
year <-c (2011, 2012, 2013, 2011, 2012, 2013, 2011, 2012, 2013)
x <- 1:10
cost <- sample(x, 9, replace=T)
spec <- as.factor(c(1, 1, 1, 2, 2, 2, 3, 3, 3))
dat <-data.frame(year=year, cost=cost, spec=spec)
# graph
library(ggplot2)
ggplot(data=dat, aes(x=year, y=cost, group=spec)) +
geom_line(aes(color=spec)) +
**geom_line(group="3", col="red")** +
scale_colour_grey() +
theme_bw()
问题显然是geom_line(group="3", col="red")
部分,但我不知道如何解决。
通过此代码,我得到了类似的奇怪信息:
list_filter
attribute [Django-doc]
答案 0 :(得分:1)
您只需定义一次aes(color = )
,然后通过命名的自定义调色板拨入您的颜色。
ggplot(data=dat, aes(x=year, y=cost, group=spec)) +
geom_line(aes(color=spec)) +
# geom_line(group="3", col="red") +
scale_color_manual(values = c("1" = "black", "2" = "grey", "3" = "red")) +
# scale_colour_grey() +
theme_bw()
答案 1 :(得分:0)
我认为这可能会解决问题,可能对melt
来说有点过头了,但是应该非常简单明了,并且是最灵活的方法,它还结合了对另一个答案的评论。
我以这个 https://stackoverflow.com/a/53264920/5795592为起点。应该足够灵活。
library(data.table)
library(dplyr)
melt(dat, measure.vars="cost", id.vars = c("year","spec") ) %>% ggplot(data=., aes(x=year, y=value)) +
geom_line(aes(color=spec), data = . %>% subset(., spec %in% c("1","2"))) +
geom_line(aes(color=spec), data = . %>% subset(., spec %in% c("3"))) +
scale_color_manual(values = c(gray.colors(2), 'red'))