I am trying to create a bump plot to visualize time series data using ggalluvial. I would like to label the center of each stratum using the value "percent" that pertains to that stratum. I cannot seem to get the labels correct. For example, the values at the top (12, 14, 8) should be in the center of the 18-30 lode, but they are found up top for some reason on the 30-40 lode. Is there a way to correctly label this? I also considered geom_sankey_bump.
df <- data.frame(age = c(
'18-30', '18-30', '18-30',
'30-40', '30-40', '30-40',
'40-50', '40-50', '40-50',
'50 ', '50 ', '50 '),
year = c(2012, 2013, 2014,
2012, 2013, 2014,
2012, 2013, 2014,
2012, 2013, 2014),
percent = c(12, 14, 8,
44, 54, 50,
21, 32, 45,
10, 13, 30))
plot <- ggplot(data =df,
aes(x = factor(year),
y = percent,
alluvium = age,
node = factor(year),
stratum = age,
label = percent) )
plot
geom_stratum(aes(stratum = age), decreasing = F, width = 3/4)
geom_alluvium(aes(fill = age), alpha = 1, decreasing = F,
width = 3/4,
knot.prop = T,
curve_type = "linear")
ggfittext::geom_fit_text(stat = "stratum", width = 1/4, min.size = 3)
ggtitle("Marijuana Crime Rate")
theme(plot.title = element_text(hjust = 0.5))
xlab(NULL)
theme_classic()
theme(legend.position = "bottom")
CodePudding user response:
To place the labels at the correct positions you have to use identical parameters for stat_stratum
, i.e. use width=3/4
and decreasing=FALSE
as you did for geom_stratum
:
library(ggplot2)
library(ggalluvial)
plot <- ggplot(data =df,
aes(x = factor(year),
y = percent,
alluvium = age,
node = factor(year),
stratum = age,
label = percent) )
plot
geom_stratum(aes(stratum = age), decreasing = F, width = 3/4)
geom_alluvium(aes(fill = age), alpha = 1, decreasing = F,
width = 3/4,
knot.prop = T,
curve_type = "linear")
ggfittext::geom_fit_text(stat = "stratum", width = 3/4, decreasing = FALSE, min.size = 3)
ggtitle("Marijuana Crime Rate")
theme(plot.title = element_text(hjust = 0.5))
xlab(NULL)
theme_classic()
theme(legend.position = "bottom")