'R: Connect bar graphs with lines filled in with matching bar color
I'm working on recreating the look of a plot found in a recent Economist article. There are two bar graphs connected by lines with the space in between them having the same color, albeit a little opaque.
I've seen this question asked but the examples only have lines connecting the bar graphs. Here's some fake data:
set.seed(0)
data_bar <- data.frame(
stringsAsFactors = F,
Sample = rep(c("A", "B"), each = 10),
Percentage = runif(20),
Taxon = rep(1:10, by = 2)
)
I've worked on reworking the linked example with no success. Any ideas?
Also in case you can't see the graph here's a screen shot:
Solution 1:[1]
This is essentially an alluvial chart, and you can use the ggalluvial package for this.
You will need to use geom_flow, as it creates the geom "in between" the bars (use geom_col for those), and you need to set curve_type = "linear".
library(ggalluvial)
#> Loading required package: ggplot2
library(tidyverse)
set.seed(0)
data_bar <- data.frame(
stringsAsFactors = F,
Sample = rep(c("A", "B"), each = 10),
Percentage = runif(20),
Taxon = rep(1:10, by = 2)
)
## first need to calcualte the actual percentage by group
data_bar %>%
group_by(Sample) %>%
mutate(perc = Percentage* 100/sum(Percentage)) %>%
ggplot(aes(y = perc, x = Sample, fill = as.character(Taxon))) +
geom_flow(aes(alluvium = Taxon), alpha= .5, color = "white",
curve_type = "linear",
width = .5) +
geom_col(width = .5, color = "white") +
scale_fill_brewer(palette = "RdBu")+
scale_y_continuous(NULL, expand = c(0,0)) +
cowplot::theme_minimal_hgrid() +
theme(panel.grid.major = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank())
#> Warning: The `.dots` argument of `group_by()` is deprecated as of dplyr 1.0.0.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.

Created on 2022-01-25 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tjebo |

