I am trying to make a plot with a few stacked bars and a dot (corresponding to their sum). However, I am having troubles giving the legend keys the positions I want. In particular, I have two questions:
- How do I get the legend for the dots to be in the same box as the legend for the bars?
- How do I rearrange the order of the legend keys for the bars to my desired order (not alphabetical)?
Here a reproducible example:
plot_data <- structure(list(unit = c("AA", "AA", "AA", "AA", "AA", "AA", "AA"
), group = c("A", "B", "C", "D", "E", "F", "G"), varZ = c(0.315095655620098,
8.47993358969688, 1.07286661490798, 0.451091277599335, -3.06214834600687,
0.356725811958313, 2.84848970770836), varA = c(0.0098613808164373,
0.641465996578336, 0.361015032231808, 0.213144088536501, 0.389915533736348,
0.0736596005037427, 0.110731973079965), varC = c(0.341579372435808,
0.330122645944357, 0.45065661072731, 0.092761187441647, 0.368695167452097,
0.542871625348926, 0.563651240617037), varD = c(-0.00427791306283325,
0.323448045179248, 0.017125289858086, 0.0177044845186174, 0.0418251685332507,
0.0367124438518658, 0.0115989629644901), varB = c(-0.101550728082657,
1.68335139006376, 0.36021358249709, -0.529840487614274, -0.199755599349737,
0.260609032586217, 0.358311578631401), varE = c(0.0694835543632507,
5.50154550075531, -0.116143900901079, 0.657321977615356, -3.66282860934734,
-0.5571269325912, 1.80419590175152)), row.names = c(NA, -7L), class = c("data.table",
"data.frame"))
## Split in two melted data tables. One with data for the stacked bars, one for the dots
bar_data <- plot_data[][, list(unit, group, varA, varB, varC, varD, varE)]
bar_data <- melt(bar_data, id.vars= c("unit", "group"))
line_data <- plot_data[][, list(unit, group, varZ)]
line_data <- melt(line_data, id.vars=c("unit", "group"))
p <-
ggplot() +
# Stacked bars
geom_col( data = bar_data,
aes( y = value,
x = group,
fill = variable
)
) +
# Point
geom_point( data = line_data,
aes( y = value,
x = group,
colour = "Z"
)
) +
theme(
legend.key.height = unit(.15,"cm"),
legend.key.width = unit(.8,"cm"),
legend.position = "bottom",
legend.title = element_blank()
) +
scale_fill_manual(values = c("#005390", "#B6C5DE", "#082A4A", "#7AACF6", "#00B0F0"),
labels = c("A", "B", "C", "D", "E")
) +
scale_color_manual(values = c("Z" = "black")) +
guides(fill = guide_legend(ncol = 2))