简体   繁体   English

如何绘制带有多个引用相同标签的点列的图例

[英]How to plot a legend with several point columns that refer to the same labels

Suppose I have this example data.frame : 假设我有这个示例data.frame

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

to which I assign a colors as follows (pardon my non-sophisticated code for this part): 我为其分配颜色的方法如下(请原谅我这部分的非复杂代码):

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)]

which I then plot: 然后我绘制:

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

在此处输入图片说明

Now I would like to add a legend which has three rows and four columns where the first column is the color.breaks and next three columns are the respective colors. 现在我想添加一个图例,该图例具有三行四列,其中第一列是颜色color.breaks和接下来的三列是各自的颜色。

Something like this: 像这样:

在此处输入图片说明

Any idea how I get this done with the legend function? 知道我如何通过legend功能完成此操作吗?

Here's a base solution, which need's some finer adjustment... 这是一个基本解决方案,需要进行一些更精细的调整...

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)

在此处输入图片说明

Crucial steps are: 关键步骤是:

  • Use ncol to specify the number of columns 使用ncol指定列数
  • Omit the labels (set them to NA) and add them afterwards (to plot them to the left) 省略标签(将它们设置为NA),然后添加(将它们绘制在左侧)
  • use trace to get the positions for the labels. 使用trace获取标签的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM