繁体   English   中英

如何在R的单个图中使用多种颜色?

[英]How to use multiple colors in a single plot in R?

x=rnorm(6000, 10, 4)
 plot(x, type = "l")

在此处输入图片说明

对于索引0-2000我想使用green color ,接下来的2000-4000红色和最后的4000-6000 blue color

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

您可以使用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")

在此处输入图片说明

这是一个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"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM