Hello,
I have hard time adding legend to my ggplot:
library(ggplot2)
MonthData <- as.data.frame(c(1:11))
MonthData$Previous <- c(1:11)
MonthData$Current <- c(12:22)
MonthData$Dynamic <- MonthData$Current/MonthData$Previous
MonthData <- MonthData[,-1]
MonthData$MonthNames <- as.character(as.roman(MonthData$Previous))
MonthData$MonthNames <- factor(MonthData$MonthNames, levels = MonthData$MonthNames)
currentYear <- 2020
previousYear <- 2019
ggplot(data = MonthData, aes(x=MonthNames)) +
coord_cartesian(ylim = c(1,30)) +
geom_line(aes(y = Previous, group = 1), color = '#feb24c', size = 0.65, linetype = "dashed")+
geom_line(aes(y = Current, group = 1), color = '#f03b20', size = 0.65, linetype = "dashed")+
geom_point(aes(y = Previous), size = 2, color = '#feb24c', pch = 17)+
geom_point(aes(y = Current), size = 2, color = '#f03b20') +
geom_col(aes(y = Dynamic/2.5 ), colour = '#bdbdbd', size = 0.65, fill = NA) +
scale_y_continuous(sec.axis = sec_axis(~.*2.5)) +
labs(
title = paste("Title"),
subtitle = paste("Circle - ", currentYear, ", Triangle - ", previousYear, ", Boxes - Dynamics."),
x = "",
y = "Title"
) +
theme_bw()
since adding legend function seems not to work properly with ggplot:
ggplot(data = MonthData, aes(x=MonthNames)) +
coord_cartesian(ylim = c(1,30)) +
geom_line(aes(y = Previous, group = 1), color = '#feb24c', size = 0.65, linetype = "dashed")+
geom_line(aes(y = Current, group = 1), color = '#f03b20', size = 0.65, linetype = "dashed")+
geom_point(aes(y = Previous), size = 2, color = '#feb24c', pch = 17)+
geom_point(aes(y = Current), size = 2, color = '#f03b20') +
geom_col(aes(y = Dynamic/2.5 ), colour = '#bdbdbd', size = 0.65, fill = NA) +
scale_y_continuous(sec.axis = sec_axis(~.*2.5)) +
labs(
title = paste("Title"),
subtitle = paste("Circle - ", currentYear, ", Triangle - ", previousYear, ", Boxes - Dynamics."),
x = "",
y = "Title"
) +
theme_bw() +
legend("bottomleft",
legend = c(currentYear, previousYear),
col = c('#feb24c', '#f03b20'),
pch = c(1,17))
giving me an error:
'strwidth(legend, units = "user", cex = cex, font = text.font)': plot.new has not been called yet
I have also tried adding shape, or colour atribute to different functions.
The legend that I'm looking at is covering caption under the Title. What I would like to see is a triangle drawing with caption, circle drawing with caption and if possible boxes drawing with caption.
I would be grateful for help,
and merry Christmas :).