I am new to Rstudio and I am attempting to add a legend to my graph but I keep getting the following error message: "Error in strwidth(legend, units = "user", cex = cex, font = text.font) : plot.new has not been called yet". I have tried a number of different methods to add the legend but I get the same error message.
This is my code I have been attempting :
ggplot(data) +
geom_segment(aes(x = 1, xend = 2, y = before, yend = after), col = 1:4) +
theme_bw() +
scale_x_discrete(
breaks = c("1", "2"),
labels = c("Before", "After"),
limits = c(1, 2)
) +
labs(y = "y", x = "x", title = "C") +legend("topright", legend=c("Mean 1", "Mean 2", "Mean 3", "Mean4"), col = 1:4)
Below is the data frame I have been working on:
before after
mean.A 55.207921 61.49175
mean.B 15.669967 20.82673
mean.C 16.250825 19.21452
mean.D 9.475262 10.69145
Any help on how to get the legend to work would be appreciated.