【问题标题】:How to plot a legend with several point columns that refer to the same labels如何绘制具有引用相同标签的多个点列的图例
【发布时间】:2014-08-19 22:14:14
【问题描述】:

假设我有这个例子data.frame:

df = data.frame(x = c(1,1,1,2,2,2,3,3,3), y = runif(9,0,0.9))

我为其分配了如下颜色(请原谅我对这部分的非复杂代码):

df$color = rep(NA, nrow(df))
color.breaks = seq(0,0.9,0.3)
colors = c("lightgray","gray","darkgray")
df$color[which(df$x == 1)] = colors[findInterval(df$y[which(df$x == 1)], color.breaks)]
colors = c("lightblue","blue","darkblue")
df$color[which(df$x == 2)] = colors[findInterval(df$y[which(df$x == 2)], color.breaks)]
colors = c("lightgreen","green","darkgreen")
df$color[which(df$x == 3)] = colors[findInterval(df$y[which(df$x == 3)], color.breaks)]

然后我绘制:

plot(x = df$x, y = df$y, col = as.character(df$col), pch = 16)

现在我想添加一个三行四列的图例,其中第一列是color.breaks,接下来的三列是各自的颜色。

类似这样的:

知道我是如何使用legend 函数完成这项工作的吗?

【问题讨论】:

    标签: r plot legend


    【解决方案1】:

    这是一个基本解决方案,需要进行一些更精细的调整...

    plot(1, type = 'n')
    l <- legend(1, 1, 
           legend = rep(NA, 9), 
           ncol = 3, pch = 16, bty="n",
           col = c("lightgray","gray","darkgray", "lightblue","blue","darkblue", 
                   "lightgreen","green","darkgreen"), trace = TRUE)
    text(l$text$x-0.05, l$text$y, c('A', 'B', 'C', rep(NA, 6)), pos = 2)
    

    关键步骤是:

    • 使用ncol指定列数
    • 省略标签(将它们设置为 NA),然后添加它们(将它们绘制到左侧)
    • 使用trace 获取标签的位置。

    【讨论】:

      猜你喜欢
      • 2012-01-14
      • 2020-02-07
      • 2019-08-10
      • 1970-01-01
      • 2019-11-08
      • 2021-07-19
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      相关资源
      最近更新 更多