堆积条形图的位置图例 [英] position legend of a stacked bar plot

查看:156
本文介绍了堆积条形图的位置图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个堆积的条形图,但是我无法定位图例,以使其不与任何条形图重叠.我尝试过使用单独的legend语句调整边距,设置xlim并在此处搜索,但都没有成功.实际上,示例数据集的代码来自StackOverflow.我正在使用基本R,并且更喜欢基本R解决方案.谢谢您的任何建议.

I am trying to create a stacked bar plot, but I cannot position the legend so that it does not overlap any of the bars. I have tried adjusting the margins, setting xlim, using a separate legend statement and searching here, all without success. Indeed, the code for the example data set came from StackOverflow. I am using base R and prefer a base R solution. Thank you for any advice.

setwd('c:/users/mmiller21/simple R programs/')

jpeg(filename = "barplot.jpeg")

set.seed(1234)
x <- replicate(8, round(10 * rexp(2000, 10)))
y <- apply(x, 2, function(column) table(factor(column, levels = 0:9)))
colnames(y) <- paste('A', seq(1,ncol(y),1), sep='')
rownames(y) <- paste('R', seq(1,nrow(y),1), sep='')
y

#      A1  A2  A3  A4  A5  A6  A7  A8
# R1  769 800 790 806 792 787 834 801
# R2  779 733 793 757 786 744 731 776
# R3  284 297 278 272 263 301 280 275
# R4  112 106  91 124 106 103 104  96
# R5   33  38  37  26  36  37  30  36
# R6   11  18   7  11  10  20  11   9
# R7    8   8   3   2   3   3   9   5
# R8    4   0   1   2   4   4   0   2
# R9    0   0   0   0   0   1   1   0
# R10   0   0   0   0   0   0   0   0

par(mfrow=c(1, 1), mar=c(5, 5, 4, 2) + 0.1)
barplot(y, col = 1:nrow(y), ylab="My Variables", legend.text = TRUE, 
        args.legend = list(x = "topright", bty = "n"))

dev.off()

推荐答案

这是怎么回事:

library(RColorBrewer)

barplot(
    y,
    xlim=c(0, ncol(y) + 3),
    col=brewer.pal(nrow(y), "Paired"),
    ylab="My Variables",
    legend.text=TRUE,
    args.legend=list(
      x=ncol(y) + 3,
      y=max(colSums(y)),
      bty = "n"
    )
)

这篇关于堆积条形图的位置图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆