如何调整R语言barplot的图例框大小及位置?
解决R语言barplot图例遮挡及位置调整问题
方法1:调整args.legend参数实现缩小+移动
直接在args.legend里补充缩放、边框和偏移参数,就能解决遮挡问题:
score <- tapply(exams$writing.score , list(exams$gender, exams$race.ethnicity ) , mean) plot1 <- barplot(score , beside = TRUE , main = "Comparison of Writing Score" , col = c("red", "lightyellow") , xlab = "Race Ethnicity Group" , ylab = "Average Writing Score" , legend.text = c("Female", "Male") , args.legend = list(x = "topright", cex = 0.8, bty = "n", inset = c(0.02, 0.02)) )
cex = 0.8:把图例文本和符号缩小到原来的80%bty = "n":去掉图例边框,减少视觉遮挡inset = c(0.02, 0.02):让图例往绘图区域内偏移一点,避免贴边同时远离柱状条
方法2:单独调用legend()函数(更灵活)
如果自带的图例参数不好控制,直接去掉legend.text,手动添加图例:
score <- tapply(exams$writing.score , list(exams$gender, exams$race.ethnicity ) , mean) # 先绘制柱状图,不附带图例 plot1 <- barplot(score , beside = TRUE , main = "Comparison of Writing Score" , col = c("red", "lightyellow") , xlab = "Race Ethnicity Group" , ylab = "Average Writing Score" ) # 手动添加图例 legend("topright", legend = c("Female", "Male"), fill = c("red", "lightyellow"), cex = 0.8, bty = "n", inset = c(0.02, 0.02))
这种方式可以精准控制所有图例属性,要是还是遮挡,还能调整inset数值,或者把位置改成topleft/bottomright,甚至用具体坐标(比如x = max(plot1) + 1, y = max(score))来定位。
内容的提问来源于stack exchange,提问作者Tye N
相关产品推荐
相关产品推荐

