如何在 ggplotly 中构建自定义条形图?

How to build customized Barchart in ggplotly?

我有带有正条和负条的条形图。我的目标是在 ggplotly 中完成,并用白色填充负值并保持边框颜色相同。

代码:

df <- data.frame (model = c("A","A","A","A","A","B","B","B","B","B"),
                  size = c("med","big","small","big","small","med","big","small","big","small"),
                  sale = c(1001,1050,-300,-150,-25,960,670,90,-105,-76),
                  area = c("med","large","narrow","large","narrow","med","large","narrow","large","narrow")
                  )



 ggplot() +
  # plot positive with fill and colour based on model
  geom_col(aes(sale, tidytext::reorder_within(size, sale, model),
               fill = size, color = size), 
           data = df,
           position = "stack") + 
  tidytext::scale_y_reordered() +
  labs(fill = "margin2") +
  facet_grid(model ~ ., switch = "y",scales = "free_y") +
  theme(axis.text.x = element_text(angle = 90),
        strip.background = element_rect(fill = "white"),
        strip.placement = "outside",
        strip.text.y.left = element_text(angle = 0),
        panel.spacing = unit(0, "lines")) + 
  theme(legend.position="none") + geom_vline(xintercept = 0)

预期输出:

您可以进行一些数据操作并添加另一层:

df %>%
  mutate(y = tidytext::reorder_within(size, sale, model)) %>%
  group_by(size, model) %>%
  mutate(sale_neg = sum(sale[sale < 0])) %>%
  ggplot(aes(sale, y, fill = size, color = size)) +
  geom_col(position = "stack") + 
  geom_col(position = 'identity', aes(x = sale_neg), fill = 'white') +
  tidytext::scale_y_reordered() +
  labs(fill = "margin2") +
  facet_grid(model ~ ., switch = "y",scales = "free_y") +
  theme(axis.text.x = element_text(angle = 90),
        strip.background = element_rect(fill = "white"),
        strip.placement = "outside",
        strip.text.y.left = element_text(angle = 0),
        panel.spacing = unit(0, "lines")) + 
  theme(legend.position="none") + geom_vline(xintercept = 0)