simple114141
simple114141

Reputation: 21

Highlighting lines and gray out rest in multiple line chart with ggplot2?

So I had generated a multiple line chart on ggplot with different countries and want to colour the top 10 and grey out the rest.

When I assign colours black and red, it colours the first two countries in the legend. However I want to colour other ones down the list. US, India, Brazil in the chart. Help much appreciated, thanks.

This is what I have: top 10 countries

and the code here:

ggplot(data=y, aes(x = Date, y = Deaths, color = Country)) +
  geom_line() +
  scale_color_manual(values = c("black",
                                "red",
                                rep("gray", 196))) 

Upvotes: 0

Views: 1384

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173928

You first need to order your countries according to the number of deaths, then in scale_color_manual you need the first 10 colours to be of your choice, not just the first two:

library(ggplot2)

y$Country <- reorder(y$Country, -y$Deaths)

ggplot(data = y, aes(x = Date, y = Deaths, color = Country)) +
  geom_line() +
  scale_color_manual(values = c(rep(c("black", "red"), each = 5),
                                rep("gray", nrow(y) - 10))) +
  guides(color = guide_none())

enter image description here

Note that since you didn't share your data, I made some up with a similar structure and the same names as yours so that the above code should also work on your own data set.

Made-up data

set.seed(1)

y <- data.frame(
  Deaths = c(replicate(198, 1000 * cumprod(runif(100, 1, 1 + sample(10, 1)/100)))),
  Date = rep(seq(as.POSIXct('2020-01-01'), as.POSIXct('2022-01-01'), len = 100),
             198),
  Country = factor(rep(1:198, each = 100)))

Upvotes: 1

Related Questions