Wincow
Wincow

Reputation: 79

stacked geom_bar without aggregating the fill values results in incorrect axis values

I am trying to create a stacked barplot that does not sum the fill values. For example, let's say I have a solution that changes color as it increases in temperature (y). I want a bar plot showing the color as it ascends the y-axis with temperature increase. I have mostly succeeded in doing this, but the y-axis ticks are incorrect

Sample data:

x<- data.frame(color = c("red", "blue", "red", "orange"), temperature = c(1, 5, 10, 20), trial = c(1, 1, 1, 1))
x
   color temperature trial
1    red           1     1
2   blue           5     1
3    red          10     1
4 orange          20     1

Note that there is only one trial, so only there will only be one bar. Also note that the color changes from red to blue when the temperature reaches 5, then changes from blue to red when the temperature reaches 10. I would like the bar to change colors in a similar way along the y-axis. When I plot it, the y-axis tick marks are wrong:

[![#Convert to factors for plotting
x$temperature<- as.factor(x$temperature)
x$color<- as.factor(x$color)][1]][1]
#plot
library(ggplot2)
ggplot(x, aes(x = trial, y = temperature, fill = color))+
  geom_bar(position = "stack", stat = "identity")

Notice in my output image, the y axis ticks do not align with the data (please note that the colors in the bar do not correspond to "color" values in the dataframe. What is happening?

enter image description here

Upvotes: 0

Views: 174

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

After you turn the values to factors, note the levels of the data.

levels(x$temperature) #This is correct
[1] "1"  "5"  "10" "20"

levels(x$color) #This is not correct
#[1] "blue"   "orange" "red"   

You need color to have the same factor levels as the order in which they appear. A simple way to do this is using fct_inorder. You can use scale_fill_identity to assign the same color to bars as in the color column.

library(tidyverse)

x %>%
  mutate(across(c(color, temperature), ~fct_inorder(as.character(.)))) %>% 
  ggplot(aes(x = trial, y = temperature, fill = color))+
  geom_bar(position = "stack", stat = "identity") + 
  scale_fill_identity()

enter image description here

Upvotes: 1

Related Questions