I am working with a graph consisting of raw numbers by year plotted as a bar chart with a secondary line graph indicating proportion.
specie <- c(rep("sorgho" , 6) , rep("poacee" , 6) , rep("banana" , 6) , rep("triticum" , 6) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 8)
year <- sample(2010:2015, 24, T)
value <- abs(rnorm(24 , 0 , 15))
test_data <- data.frame(specie,condition,year,value) %>%
arrange(year, condition)
smrydata <-
test_data %>%
group_by(year) %>%
mutate(total = sum(value)) %>%
group_by(condition, year) %>%
summarise(value = sum(value),
prop = value/total,
.groups = "drop") %>%
arrange(year, condition) %>%
distinct()
Max <- max(smrydata$value)
ggplot(smrydata, aes(year, value, group = 1)) +
scale_linetype_manual("My Legend", values = 1) +
geom_col(fill = "steelblue") +
geom_line(aes(y = prop * Max, linetype = "%"), colour = "orange", size = 2) +
scale_y_continuous(sec.axis = sec_axis( ~ ./Max, labels = scales::percent)) +
theme_bw() +
facet_wrap(~condition) +
theme(legend.position = "bottom")
When I run this code, I can produce my graph with a legend for the proportion line, but I'm not sure how to produce the legend for the bar chart. Ideally they should appear together grouped with the legend title ("My Legend"), and I would prefer the bar chart legend to appear on top of the line legend (blue "n", orange "%").
(This is not the real data I'm working with, so I am not concerned about some issues with the current plot caused by incomplete data, such as the proportions line not being "0%" when there are no corresponding values)


