繁体   English   中英

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

[英]ggplot: Combine stacked and dodge in barplot

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

我正在使用的数据子集如下。

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 个条形,每种技术(闪避)一个。 然后每个条形都应该将预测堆叠在最后一个值预测之上。

任何帮助表示赞赏。

我知道你不喜欢 facet 的想法,但是你可以很容易地调整外观,使它们看起来像一个连续的图形,所以也许你仍然可以考虑这样的事情:

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 包( v2.0.0 ) 于 2021 年 6 月 25 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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