R语言报错Error in strwidth: plot.new has not been called yet 修复方案咨询
legend() in R Hey there, let's break down this error you're hitting. The core issue is super straightforward: you're trying to add a legend to a plot that doesn't exist yet. R's legend() function needs an active plotting canvas (created by functions like plot(), hist(), or ggplot()) to know where to place the legend. Without that canvas already rendered, it throws this error.
Here are actionable fixes to resolve this:
1. Always create your base plot first
Before callinglegend(), make sure you've generated your main plot with a function that initializes the plotting device. For example:# First render your base plot plot(1:10, 1:10, main = "My Scatter Plot") # Now add the legend to the existing plot legend("topright", legend = "Sample Data", pch = 1, col = "blue")If you're using ggplot2, note that you don't call
legend()directly—usescale_*()functions ortheme()to adjust legends, which automatically tie to the plot you've built.2. Double-check your code order
This error often happens from a simple ordering mistake: yourlegend()call is placed before your plot-generating code. For example, if you copied code blocks and rearranged them accidentally, just swap the order so the plot comes first.3. Ensure your plot is actually rendered (especially for ggplot2)
If you're assigning a ggplot object to a variable, you need to explicitly print it to create the canvas:library(ggplot2) # Build the plot object my_ggplot <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point(aes(color = factor(cyl))) # Render the plot first print(my_ggplot) # Now you can adjust legends via ggplot's built-in functions (no need for base R's legend())Alternatively, just run the ggplot code without assigning it to a variable—R will render it automatically if it's the last line in your script or chunk.
4. Reset the plotting device if it's stuck
If previous plot errors left your plotting device in a broken state, rundev.off()to close any open plot windows, then rerun your plot and legend code from scratch.
If you're working in RStudio, also make sure the "Plots" pane isn't frozen or hidden—sometimes rendering glitches can prevent the canvas from initializing properly.
内容的提问来源于stack exchange,提问作者Kevin Chiang

