简体   繁体   English

基本R水平图例 - 有多行

[英]Base R horizontal legend - with multiple rows

I wish to create a horizontal legend with multiple rows using base R (not ggplot). 我希望使用基数R(而不是ggplot)创建一个包含多行的水平图例。 There is an option for multiple columns but not multiple rows in legend(). 在legend()中有多个列但没有多行的选项。 Is there a way to do this? 有没有办法做到这一点? Example to play with below where the horizontal legend it too wide for the plot. 下面的例子,其中水平图例对于图表来说太宽了。

MyCol <- topo.colors(20)
barplot(rep(1,20), yaxt="n", col=MyCol)
x <- 1:20
MyLab <- paste("Zone",x)
legend("bottom",MyLab,fill=MyCol,horiz=T)

You can use the ncol = parameter instead of horiz to get the layout you want. 您可以使用ncol =参数而不是horiz来获取所需的布局。 Note that horiz overrides ncol , so don't use both together. 请注意, horiz会覆盖ncol ,因此请勿同时使用这两者。 Although, this does not specify the number of rows directly, it does do so indirectly, because the number of rows is determined by the number of columns and factors. 虽然这没有直接指定行数,但它间接地指定了行数,因为行数由列数和因子确定。

MyCol <- topo.colors(20)
barplot(rep(1,20), yaxt="n", col=MyCol)
x <- 1:20
MyLab <- paste("Zone",x)
legend("bottom",MyLab,fill=MyCol,ncol=5)

在此输入图像描述

If you want to arrange the legend items ordered along rows, you can do this by indexing them in the order you want. 如果要排列沿行排序的图例项,可以按所需顺序对其进行索引。 Eg 例如

MyOrder = matrix(1:20, nrow = 4, ncol = 5, byrow = T)
legend("bottom",MyLab[MyOrder], fill=MyCol[MyOrder] ,ncol=5)

在此输入图像描述

To generalize for different numbers of rows and factors, we can do something like 为了概括不同数量的行和因子,我们可以做类似的事情

Nfact = 21
Nrows = 5
Ncols = ceiling(Nfact / Nrows)
MyOrder = matrix(1:(Nrows*Ncols), nrow=Nrows, ncol=Ncols, byrow=T)

MyCol <- topo.colors(Nfact)
x <- 1:Nfact
MyLab <- paste("Zone",x)

barplot(rep(1,Nfact), yaxt="n", col=MyCol)
legend("bottom", MyLab[MyOrder], fill = MyCol[MyOrder], ncol = Ncols, border=NA)

在此输入图像描述

And a final extra trick: In the previous plot, we set border=NA. 最后一个额外的技巧:在上一个图中,我们设置border = NA。 This is to prevent borders being drawn around empty legend items (those at the bottoms of incomplete columns). 这是为了防止在空图例项目(不完整列底部的项目)周围绘制边框。 If you want borders, then we should also create a vector of border colours that is NA only in the locations we don't want to draw. 如果你想要边框,那么我们也应该创建一个边框颜色矢量,只有在我们不想绘制的位置才是NA

MyBorders = rep("black", Nrows*Ncols)
MyBorders[MyOrder > Nfact] <- NA
legend("bottom", MyLab[MyOrder], fill = MyCol[MyOrder], ncol = Ncols, border=MyBorders)

在此输入图像描述

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

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