【问题标题】:Grayscale line graph and one line in red灰度折线图和一条红线
【发布时间】:2019-08-22 12:46:07
【问题描述】:

我想创建一个包含多个组 (~10) 的灰度线图,但有一条线 (spec=3) 是红色的。

请看下面只有 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") 部分,但我不知道如何解决。

使用这段代码,我得到了一些奇怪的东西:

【问题讨论】:

    标签: r ggplot2


    【解决方案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()
    

    【讨论】:

    • 如果你想要很多灰度颜色和一种红色,你可以像这样自定义色阶:scale_color_manual(values = c(gray.colors(9), 'red'))
    【解决方案2】:

    我认为这可能会奏效,使用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')) 
    

    【讨论】:

      猜你喜欢
      • 2014-06-16
      • 2014-04-10
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 2013-06-29
      • 1970-01-01
      • 2019-10-27
      相关资源
      最近更新 更多