ggplot:在条形图中组合堆叠和躲避

时间:2021-06-24 00:29:37

标签: r ggplot2

正如标题所暗示的,我想在条形图中结合堆叠和闪避。 Stack Overflow 中的大多数答案(例如 this)都建议使用 facet wrapping。我不想这样做,因为我有其他不使用刻面包装的图形,而且我不希望美感有所不同。最接近我想要达到的结果的答案是 this 一。但是,我想避免为所有闪避值手动创建数据框。

我使用的数据子集如下。

benchmark <- c("correlation", "correlation", "correlation", "covariance", "covariance", "covariance")
technique <- c("last_value", "dyna", "tage", "last_value", "dyna", "tage")
last_value_predictions <- c(1361, 1336, 453, 1865, 1841, 556)
predictions <- c(0, 25, 908, 0, 24, 1309)
df <- data.frame(benchmark, technique, last_value_predictions, predictions)

我想要 x 轴上的基准。每个基准应该有 3 个条形,每种技术(闪避)一个。然后每个条形都应该将预测堆叠在最后一个值预测之上。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我知道您不喜欢分面的想法,但是您可以轻松调整外观,使它们看起来像一个连续的图形,所以也许您仍然可以考虑这样的事情:

benchmark <- rep(c("correlation", "covariance"), each=3)
technique <- rep(c("last_value", "dyna", "tage"), 2)
last_value_predictions <- c(1361, 1336, 453, 1865, 1841, 556)
predictions <- c(0, 25, 908, 0, 24, 1309)
df <- data.frame(benchmark, technique, last_value_predictions, predictions)

library(ggplot2)
library(cowplot)
library(dplyr)
library(tidyr)
pivot_longer(df, ends_with("predictions")) %>% 
    mutate(technique=factor(technique, unique(technique)),
        name=factor(name, rev(unique(name)))) %>% 
    ggplot(aes(x=benchmark, y=value, fill=name)) + 
    geom_col() + 
    theme_cowplot() +
    facet_wrap(.~technique, strip.position = "bottom")+
        theme(strip.background = element_rect(colour=NA, fill="white"), 
            panel.border=element_rect(colour=NA),
            strip.placement = "outside",
            panel.spacing=grid::unit(0, "lines"), 
            legend.position = "bottom") + 
        scale_fill_manual(values=c("blue", "grey"))

编辑: 当然,您可以根据需要切换 benchmarktechnique

编辑 #2: 图例调整可以通过一个小的额外 hack 来实现(不知道为什么会失败),并且可以旋转标签以清理您发布的图像结果的外观。

p <- pivot_longer(df, ends_with("predictions")) %>% 
    mutate(technique=factor(technique, unique(technique)),
        name=factor(name, rev(unique(name)))) %>% 
    ggplot(aes(x=technique, y=value, fill=name)) + 
    geom_col() + 
    theme_cowplot() +
    facet_wrap(.~benchmark, strip.position = "bottom")+
        theme(strip.background = element_rect(colour=NA, fill="white"), 
            panel.border=element_rect(colour=NA),
            strip.placement = "outside",
            panel.spacing=grid::unit(0, "lines"), 
            legend.position = "bottom",
            axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
        scale_fill_manual(values=c("blue", "grey"))
p2 <- p + theme(legend.position = "none")
leg <- as_grob(ggdraw(get_legend(p), xlim = c(-.5, 1)))
cowplot::plot_grid(p2, leg, nrow = 2, rel_heights = c(1, .1))

reprex package (v2.0.0) 于 2021 年 6 月 25 日创建

相关问题