Hugh Warden
Hugh Warden

Reputation: 446

Add a gradient fill to geom_col

Here is come basic code for a column plot:

library(tidyverse)

diamonds %>%
  group_by(cut) %>%
  summarise(
    count = n()
  ) %>%
  ggplot(
    aes(
      x = cut,
      y = count,
      fill = count
    )
  ) +
  geom_col() +
  scale_fill_viridis_c(
    option = "plasma"
  )

basic col plot

I could not find any examples of what I would like to do so I will try and explain it as best I can. I have applied a colour gradient to the fill aesthetic which colours the whole column plot one colour. Is it possible to have it such that each column of the plot contains the full colour spectrum up until it's respective value?

By which I mean the "Ideal" column of my plot would look exactly like the key in the legend. Then the "Premium" column would look like the key in the legend but cut off ~2/3 of the way up.

Thanks

Upvotes: 2

Views: 1158

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You can do this fairly easily with a bit of data manipulation. You need to give each group in your original data frame a sequential number that you can associate with the fill scale, and another column the value of 1. Then you just plot using position_stack

library(ggplot2)
library(dplyr)

diamonds %>%
  group_by(cut) %>%
  mutate(fill_col = seq_along(cut), height = 1) %>%
  ggplot(aes(x = cut, y = height, fill = fill_col)) +
  geom_col(position = position_stack()) +
  scale_fill_viridis_c(option = "plasma")

enter image description here

Upvotes: 4

Related Questions