Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ggplot2: adding more lines in a spesific color

I’m trying to add more lines to my line chart. How do I ensure that all newly added lines are greyed out?

first4letters <- c(rep("A", 3), rep("B", 3), rep("C", 3), rep("D", 3))
times <- rep(c("time1", "time2", "time3"), 4)
score <- c(5, 10, 2, 3, 4, 7, 11, 2, 9, 4, 6, 11)

df <- data.frame(first4letters, times, score)
df

plot1 <- ggplot(data = df, aes(times, score, group = first4letters)) + 
  geom_line(aes(color = first4letters)) +
  geom_point(aes(color = factor(first4letters)), size = 1) +
  theme_classic()
plot1 + scale_color_manual(values = c("red", "blue", "black", "orange")) 

I will add some new letters. However, the lines showing these letters must be gray. I cannot add a new value to the scale_color_manual() function. Because the function determines the order of the colors itself.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option would be to use a named vector of colors. Doing so, all other categories are automatically assigned the na.value=:

Adding two more letters to your example data:

library(ggplot2)

first4letters <- c(
  rep("A", 3), rep("B", 3),
  rep("C", 3), rep("D", 3),
  rep("E", 3), rep("F", 3)
)
times <- rep(
  c("time1", "time2", "time3"), 6
)
score <- c(
  5, 10, 2, 3, 4, 7, 11, 2, 9, 4,
  6, 11, 3, 8, 9, 10, 12, 3
)

df <- data.frame(first4letters, times, score)

pal_color <- c("red", "blue", "black", "orange")
names(pal_color) <- LETTERS[1:4]

ggplot(data = df, aes(times, score, group = first4letters)) +
  geom_line(aes(color = first4letters)) +
  geom_point(aes(color = factor(first4letters)), size = 1) +
  theme_classic() +
  scale_color_manual(values = pal_color, na.value = "grey80")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading