0

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?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
user17549713
  • 84
  • 1
  • 10
  • 1
    Please post your data with ```dput()``` instead of an image. – Shibaprasadb Dec 14 '21 at 14:42
  • Does this answer your question? [Fixing the order of facets in ggplot](https://stackoverflow.com/questions/14262497/fixing-the-order-of-facets-in-ggplot) – mhovd Dec 14 '21 at 14:49
  • 1
    I've linked to the FAQ about ordering bars in ggplot. If you need more help than that, please edit your question to share your code and sample data as copy/pasteable text, not as pictures. – Gregor Thomas Dec 14 '21 at 14:52

1 Answers1

2

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))
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294