Home > database >  Order by a value within a "fill" variable ggplot - Bar Chart R
Order by a value within a "fill" variable ggplot - Bar Chart R

Time:12-15

I have the following dataset:

Data:

test <- data.frame(
cluster   = c("1", "2", "3","1", "2", "3","1", "2", "3",), 
variable   = c("age", "age", "age", "speed", "speed", "speed", "price","price","price",),
value = c(0.33,0.12,0.98,0.77,0.7,0.6,0.11,0.04,0.15))

test$variable <- factor(test$variable, levels = c("age","speed","price"))

Code

test %>%
  ggplot(aes(x = cluster, y = value ,fill = variable ,group = (cluster)))  
  geom_col(position = "stack", color = "black", alpha = .75)  
  coord_flip()

I try to order the bar chart by a value within variable, for exampel "age".This is my code i used to visualize the chart, and i already tried the order function, but that doesnt seems to be possible within the "fill" argument.

Think the problem is, that "age" itself is just a value of "variable".

BarChart

It should be like following:

Ordered Barchart

Is it at all possible to display something like this with ggplot or do i need another package?

CodePudding user response:

You've adjusted the level order of variable, which will affect the order of the fill colors within each bar. To change the order of the axis where you mapped x = cluster, we need to adjust the order of the levels of cluster. As a one-off, you can do this manually. It's a little bit more work to do it responsively:

Manually:

test$cluster = factor(test$cluster, levels = c(2, 1, 3))

Calculating the right order:

library(dplyr)
level_order = test %>%
  filter(variable == "age") %>%
  group_by(cluster) %>%
  summarize(val = sum(value), .groups = "drop") %>%
  arrange(val) %>% 
  pull(cluster)

test = mutate(test, cluster = factor(cluster, levels = level_order))
  • Related