0

I know my question looks similar to many others but I had not founded the solution to my problem.

I have these two bar charts, and I want to order the two charts by the value of "ALPHA". enter image description here

In my desired output, the values on the y-axis are: E,D, B,C, A

This is my dataset and the code for the plot:

set.seed(123)
df <- data.frame(
  X = c(runif(5, 0,1000), runif(5, -500,500)),
  Y = rep(LETTERS[1:5],2),
  Z = c(rep("ALPHA",5),rep("BETA",5))
)
ggplot(df, aes(y = Y, x = X)) +
  geom_bar(stat = "identity", fill = "steelblue") +
  facet_grid(. ~ Z, scales = "free_x", space = "free_x") +
  labs(y = "", x = "", title = "This is my visualization")

Thanks in advance

3 Answers3

0
library(tidyverse)
set.seed(123)

df <- data.frame(
  X = c(runif(5, 0,1000), runif(5, -500,500)),
  Y = rep(LETTERS[1:5],2),
  Z = c(rep("ALPHA",5),rep("BETA",5))
)

# determine order
level_order <- df |> 
  filter(Z == "ALPHA") |> 
  arrange(X) |> 
  pull(Y)

# convert to factor in that order
df <- df |> 
  mutate(Y = factor(Y, levels = level_order))

# plot
ggplot(df, aes(y = Y, x = X)) +
  geom_bar(stat = "identity", fill = "steelblue") +
  facet_grid(. ~ Z, scales = "free_x", space = "free_x") +
  labs(y = "", x = "", title = "This is my visualization")

Created on 2023-03-22 with reprex v2.0.2

dufei
  • 2,166
  • 1
  • 7
  • 18
0

Here's an option:

library(tidyverse)

set.seed(123)
df <- data.frame(
  X = c(runif(5, 0,1000), runif(5, -500,500)),
  Y = rep(LETTERS[1:5],2),
  Z = c(rep("ALPHA",5),rep("BETA",5))
) %>% 
  group_by(Y) %>% 
  mutate(
    total = ifelse(Z == "ALPHA", X, NA)
  ) %>% 
  fill(total, .direction = 'down')

ggplot(df, aes(y = reorder(Y, total), x = X)) +
  geom_bar(stat = "identity", fill = "steelblue") +
  facet_grid(. ~ Z, scales = "free_x", space = "free_x") +
  labs(y = "", x = "", title = "This is my visualization")

Matt
  • 7,255
  • 2
  • 12
  • 34
0

You can do like this:

library(dplyr) # must be dplyr >= 1.1
df |>
  mutate(order = X[Z == "ALPHA"], .by = Y) |>
  ggplot(aes(y = reorder(Y, order), x = X)) +
  geom_bar(stat = "identity", fill = "steelblue") +
  facet_grid(. ~ Z, scales = "free_x", space = "free_x") +
  labs(y = "", x = "", title = "This is my visualization")

enter image description here

You are creating a new column equal to the value X when Z is equal to ALPHA and you use it to reorder Y

Edo
  • 7,567
  • 2
  • 9
  • 19