Let's say I have a dataset that I am going to analyze using an RShiny App.
The columns are: State, City, GDP, Year.
The first plot is:
ggplot(aes(x = Year, y = GDP, fill = State))
geom_col()
Then the second plot has a Select Input which will be the State.
The second plot code is:
ggplot(aes(x = Year, y = GDP, fill = City))
geom_col()
So basically, if the state of Illinois is green in the first plot, I would like the cities of Illinois to be shades of green on the second plot. Is there a way I can do this?
Thank you.
CodePudding user response:
Sure could that be achieved. You simply have to create a state color palettes which assign a color to each state and a city color palette which assigns to each city a shade of the state color. The hard work is to create these color palettes for which I make use of dplyr
and colorspace::lighten
to create the shades.
Using some fake example data:
library(ggplot2)
library(dplyr, warn = FALSE)
library(tibble)
library(colorspace)
# Make color palettes
pal <- dat |>
distinct(State, City) |>
mutate(state_fill = ifelse(State == "Illinois", "darkgreen", "steelblue")) |>
group_by(State, state_fill) |>
summarise(City = City,
city_fill = colorspace::lighten(state_fill, seq(0.05, .5, length.out = n())), .groups = "drop")
state_pal <- distinct(pal, State, state_fill) |> deframe()
city_pal <- distinct(pal, City, city_fill) |> deframe()
dat$City <- factor(dat$City, unique(dat$City))
ggplot(dat, aes(x = Year, y = GDP, fill = State))
geom_col()
scale_fill_manual(values = state_pal)
labs(title = "State")
ggplot(dat, aes(x = Year, y = GDP, fill = City))
geom_col()
scale_fill_manual(values = city_pal)
labs(title = "City")
DATA
dat <- data.frame(
Year = 2016:2020,
State = c(rep("Illinois", 15), rep("Missouri", 10)),
City = rep(c("Chicago", "Rockford", "Springfield", "Kansas City", "St. Louis"), each = 5),
GDP = 1:25
)