Suppose I have this example 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.
Something like this:
Any idea how I get this done with the legend
function?
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:
ncol
to specify the number of columns trace
to get the positions for the labels.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.