subset data by legend selection- ggplotly geom_bar

35 Views Asked by At

I wonder how can I reorder bar plot in ggplotly using only bars that belong to the groups I selected from the legend

Having DF with many Observations that comes from several groups, I made geom_bar that shows the top 20 Observations ordering DESC by their y values with fill = Group, if I choose from the legend to show only part of the groups I wish to get the top 20 Observations from the selected groups

ggplotly(ggplot(DF %>%arrange(desc(y)) %>%  
                  slice(1:20) , aes(x = reorder(Obs, -y), y = y)) +
           geom_bar(aes(x = reorder(Obs, -y),y = y, fill = Group)), stat = "identity", width = 0.8) 
1

There are 1 best solutions below

1
Uana On

Hope I understood well:

# Example data frame
set.seed(42)
DF <- data.frame(
  Obs = rep(letters, each = 3),
  Group = rep(c("A", "B", "C"), times = 26),
  y = runif(78)
)

# Select only groups "A" and "C"
selected_groups <- c("A", "C")

# Subset the data to include only selected groups
subsetted_DF <- subset(DF, Group %in% selected_groups)

# Create the reordered bar plot
your_ggplot <- ggplot(subsetted_DF %>% arrange(desc(y)) %>% slice(1:20), aes(x = reorder(Obs, -y), y = y, fill = Group)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Top 20 Observations by y value (Descending)",
       x = "Observations",
       y = "y value") +
  theme_minimal()

# Create ggplotly
your_ggplotly <- ggplotly(your_ggplot) 

# Print 
your_ggplotly