You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言报错Error in strwidth: plot.new has not been called yet 修复方案咨询

Fixing "plot.new has not been called yet" Error When Using 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 calling legend(), 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—use scale_*() functions or theme() 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: your legend() 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, run dev.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:22:01