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.
legend() is a base R function, you can't apply a base R function to a ggplot2 object. Is this what you want to achieve?
library(tidyverse)
# Sample data in a copy/paste friendly format, replace this with your own data frame
sample_df <- data.frame(
row.names = c("mean.A", "mean.B", "mean.C", "mean.D"),
before = c(55.207921, 15.669967, 16.250825, 9.475262),
after = c(61.49175, 20.82673, 19.21452, 10.69145)
)
# Relevant code
sample_df %>%
rownames_to_column(var = "Mean") %>%
ggplot() +
geom_segment(aes(x = 1L, xend = 2L, y = before, yend = after, col = Mean)) +
theme_bw() +
scale_x_discrete(
breaks = c(1, 2),
labels = c("Before", "After"),
limits = factor(c(1, 2))
) +
labs(y = "Mean concentration of Enzyme (IU/l)/Pigement (μmol/l) Present",
x = "Treatment Stage",
title = "Concentration of Various Enyzmes Before and After Treatment")
Minor footnote, should you ever be using legend() in {base}: The legend() function operates on one plot at a time and can't be called successively for the same plot.
Somewhat off topic: Does this data benefit from graphical presentation compared to a table?