MNU
MNU

Reputation: 764

How to use multiple colors in a single plot in R?

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

enter image description here

For index 0-2000 I would like to use green color and for the next 2000-4000 red and for the final 4000-6000 blue color.

How can I color this plot with multiple color?

Upvotes: 2

Views: 644

Answers (2)

cardinal40
cardinal40

Reputation: 1263

Here's a ggplot solution:

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"))

Upvotes: 1

dc37
dc37

Reputation: 16178

You can use lines and specify a x position to draw x values in different colors:

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")

enter image description here

Upvotes: 2

Related Questions