bump chart - line colour based on ranking

Hi everyone,

I have a bump chart (geom_line, x axis = month/year, y = ranking) where I'm trying to have the top 3 streets have random colours and the others are all grey. I've created another column called rank_colour2 and have specified that anything ranking from 4-10 is "grey" and the rest "na" in hopes that geom_line would just fill in na with a random colour. This didn't work so I tried to create a vector of colours based on the rank colour. That didn't work either.

Here's the code I have, any assistance would be appreciated.

socialdisorder_concentration_preFEWC <- socialdisorder_concentration_preFEWC %>%
mutate(rank_colour2 = case_when(is.na(rank.y) & is.na (rank_colour) ~ "grey",
rank.y >= 4 & rank.y <= 10 ~ "grey",
rank.y == 1 ~ "red",
rank.y == 2 ~ "orange",
rank.y == 3 ~ "green"))

colours <- c("red", "red", "orange", "orange", "green", "green", "grey", "grey")

socialdisorder_concentration_preFEWC$mthyr <- as.factor (socialdisorder_concentration_preFEWC$mthyr)

ggplot(data = socialdisorder_concentration_preFEWC, aes(x = mthyr, y = rank.x, group = blockstreet))+
geom_line (aes(color = rank_colour2), linewidth = 1) +
geom_point(aes(color = rank_colour2)) +
scale_x_discrete(name = "Month-Year") +
scale_y_reverse(name = "Rank", breaks = seq (1,10, by = 1)) +
scale_colour_manual (values = colours)

You could try with a named vector: Using Named Colors with ggplot2 - John Quensen (john-quensen.com)

Otherwise, your code isn't reproducible as we don't have an example of your dataset.

What happens if you try this?

socialdisorder_concentration_preFEWC |> 
  ggplot(aes(x = mthyr, y = rank.x, group = blockstreet))+
  geom_line (aes(color = rank_colour), linewidth = 1) +
  geom_point(aes(color = rank_colour)) +
  scale_x_discrete(name = "Month-Year") +
  scale_y_reverse(name = "Rank", breaks = seq (1,10, by = 1)) +
  scale_colour_identity()

The package gghighlighter lets you add colors based on conditionals. Also, I believe the package ggcharts has similar functions.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.