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.
A minimal reproducible example consists of the following items:
A minimal dataset, necessary to reproduce the issue
The minimal runnable code necessary to reproduce the issue, which can be run
on the given dataset, and including the necessary information on the used packages.
Let's quickly go over each one of these with examples:
Minimal Dataset (Sample Data)
You need to provide a data frame that is small enough to be (reasonably) pasted on a post, but big enough to reproduce your issue.
Let's say, as an example, that you are working with the iris data frame
head(iris)
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1 5.1 3.5 1.4 0.…
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()
ReesM
March 25, 2024, 11:55pm
4
The package gghighlighter lets you add colors based on conditionals. Also, I believe the package ggcharts has similar functions.
1 Like
system
Closed
April 15, 2024, 11:56pm
5
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.