【问题标题】:How to use multiple colors in a single plot in R?如何在 R 中的单个图中使用多种颜色?
【发布时间】:2020-05-09 02:05:38
【问题描述】:
x=rnorm(6000, 10, 4)
 plot(x, type = "l")

对于索引0-2000,我想使用green color,下一个2000-4000 red 和最后一个4000-6000 blue color

如何用多种颜色为该图着色?

【问题讨论】:

    标签: r plot colors


    【解决方案1】:

    您可以使用lines 并指定x 位置来绘制不同颜色的x 值:

    x=rnorm(6000, 10, 4)
    plot(x[1:2000], type = "l", xlim = c(0,6000), col = "green")
    lines(x = 2000:4000, y = x[2000:4000], col = "red")
    lines(x = 4000:6000, y = x[4000:6000], col = "blue")
    

    【讨论】:

      【解决方案2】:

      这是一个 ggplot 解决方案:

      library(tidyverse)
      
      df <- 
        x %>% 
        enframe(name = "Index") %>% 
        mutate(
          color = case_when(
            Index <= 2000 ~ "green", 
            Index <= 4000 ~ "red",
            TRUE ~ "blue"
          )
        )
      
      df %>% 
        ggplot(aes(x = Index, y = value, color = color)) +
        geom_line(show.legend = FALSE) +
        scale_color_manual(values = c("blue" = "blue", "green" = "green", "red" = "red"))
      

      【讨论】:

        猜你喜欢
        • 2013-03-18
        • 2015-02-11
        • 2021-03-02
        • 2015-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 1970-01-01
        相关资源
        最近更新 更多