简体   繁体   中英

How to make grouped bar chart interactive?

Here is data of sales by year and model. Now I want to rank/order these models by the following:

models are ordered from top to down according to their sales in each.

Now I want to visualize this chart via ggplotly() to make it interactive.

library(purrr)
library(forcats)

df_agg <- df %>% 
  group_by(Year) %>%
  mutate(Share = sales / sum(sales), Year2 = Year) %>%
  mutate(across(Share, ~ round(., 4))) %>% 
  group_by(Year) %>% 
  group_map(~ .x %>% 
              mutate(model = fct_reorder(model, Share, .desc = TRUE) %>% 
                             fct_relevel("J", after = Inf)) %>% 
              rename(Year = Year2))

## base plot

bp <- ggplot() +
  scale_x_continuous(breaks = seq(min(df$Year), max(df$Year), 2))+
  scale_y_continuous(labels = scales::percent)

reduce(df_agg, ~ .x + 
         geom_col(aes(x = Year, y = Share, fill = model), data = .y, 
                               position = "fill", width = 1, color = "white") +
         geom_text(aes(x = Year, y = Share, fill = model,
                       label = scales::percent(Share, accuracy = 0.1)),
                   data = .y,
                   position = position_fill(vjust = 0.50),
                   color = "black", size = 2), .init = bp)

在此处输入图像描述

A quick n' dirty solution is plotly :

library(plotly)
plotly::ggplotly(bp)

Well, it does (as I told you already in the comment in your previous question ):

library(plotly)

reduce(df_agg, ~ .x + 
         geom_col(aes(x = Year, y = Share, fill = model), data = .y, 
                               position = "fill", width = 1, color = "white") +
         geom_text(aes(x = Year, y = Share, fill = model,
                       label = scales::percent(Share, accuracy = 0.1)),
                   data = .y,
                   position = position_fill(vjust = 0.50),
                   color = "black", size = 2), .init = bp) %>%
ggplotly()

Plotly 图表的图片

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM