【问题标题】:Legend disappaers when plotting in R在 R 中绘图时图例消失
【发布时间】:2017-11-17 23:57:24
【问题描述】:

我已经绘制了五个图表和一个图例。图表工作得很好,但是图例消失而没有错误。 My preview in RStudio looks like this

当我放大时,图例应该是空白的区域。 我使用以下代码:

opar <- par (no.readonly = TRUE)
par (mfrow = c(3, 2))

library(deSolve)

# Plot A
LotVmod <- function (Time, State, Pars) {
    with(as.list(c(State, Pars)), {
        dx = (b*x) - (b*x*x/K) - (y*(x^k/(x^k+C^k)*(l*x/(1+l*h*x))))
        dy = (y*e*(x^k/(x^k+C^k)*(l*x/(1+l*h*x)))) - (m*y)
        return(list(c(dx, dy)))
    })
}

Pars <- c(b = 1.080, e = 2.200, K = 130.000, k = 20.000, l = 2.000, 
          h = 0.030, C = 2.900, m = 0.050)

State <- c(x = 0.25, y = 2.75)  
Time <- seq(1, 9, by = 1)

out <- as.data.frame(ode(func = LotVmod, y = State, parms = Pars, times = Time))

matplot(out[,-1], type = "l", xlim = c(1, 9), ylim = c(0, 45),  
        xlab = "time", 
        ylab = "population",
        main = "Compartment A")
mtext ( "Coefficient of Variance 4.96", cex = 0.8 )

x <- c(# Validation data)
y <- c(# Validation data)

lines (Time, x,  type="l", lty=1, lwd=2.5, col="black") 
lines (Time, y, type="l", lty=1, lwd=2.5, col="red")

# Legend
plot.new()
legend("center", c(expression (italic ("F. occidentalis")*" observed"), 
                   expression (italic ("M. pygmaeus")*" observed"), 
                   expression (italic ("F. occidentalis")*" simulated"),
                   expression (italic ("M. pygmaeus")*" simulated")),
       lty = c(1, 1, 1, 2), 
       col = c(1, 2, 1, 2), 
       lwd = c(2.5, 2.5, 1, 1),
       box.lwd = 0, bty = "n")

# Plot C to F = same as A

par(opar)

我的输出没有给出错误。我之前使用过完全相同的代码没有任何问题,因此我重新启动了 R,删除了所有对象,清除了所有绘图并重新启动了 RStudio 和我的计算机。

【问题讨论】:

    标签: r plot legend


    【解决方案1】:

    尝试在您的图例语句中添加xpd=TRUE。即

    legend("center", c(expression (italic ("F. occidentalis")*" observed"), 
                       expression (italic ("M. pygmaeus")*" observed"), 
                       expression (italic ("F. occidentalis")*" simulated"),
                       expression (italic ("M. pygmaeus")*" simulated")),
           lty = c(1, 1, 1, 2), 
           col = c(1, 2, 1, 2), 
           lwd = c(2.5, 2.5, 1, 1),
           box.lwd = 0, bty = "n", xpd=TRUE)
    

    默认情况下,图例被绘图区域截断。这个xpd 参数可以在绘图区域之外进行绘图。参见例如?par 了解更多关于xpd

    【讨论】:

    • 将其设置为 TRUE 会更好。
    • @JorisMeys 确实如此。我没记错。现已更新。
    【解决方案2】:

    这是由于绘图画布的设置方式以及重新缩放该设备的工作方式。你这样做的方式是在右上角的绘图区域中添加图例。然而,绘图区域不是完整的设备,而只是由轴形成的空间内的一部分。如果重新缩放,该绘图区域也将重新缩放。绘图区域周围的边距不会改变大小,因此放大会使绘图区域变得如此之小,以至于不再适合图例。它被绘图区域周围的边缘隐藏。

    因此 AEBilgrau 非常正确,您需要添加 xpd = TRUE。这允许图例延伸到绘图区域之外,因此在调整绘图设备大小时它不会消失在边距后面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2022-06-22
      • 2017-02-01
      • 1970-01-01
      相关资源
      最近更新 更多