R图例放置在图中

scr*_*Owl 33 plot r legend

我有一个情节,其数据可以进入我想用于传奇的区域.有没有办法让绘图自动放在最高数据点上方的标题空间以适应图例?

如果我手动输入ylim()参数来扩展大小然后给出我想要传说所在位置的确切坐标,我可以让它工作,但我更喜欢有一个更灵活的方法来做这个,因为它是一个前端数据库查询和数据级别可能具有非常不同的级别.

在此输入图像描述

aat*_*lob 28

编辑2017:

使用ggplot和theme(legend.position =""):

library(ggplot2)
library(reshape2)

set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)

df = data.frame(number = 1:5,a,b,c)
df_long <- melt(df,id.vars = "number")
ggplot(data=df_long,aes(x = number,y=value, colour=variable)) +geom_line() +
theme(legend.position="bottom")
Run Code Online (Sandbox Code Playgroud)

原始答案2012:将图例放在底部:

set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)

dev.off()

layout(rbind(1,2), heights=c(7,1))  # put legend on bottom 1/8th of the chart

plot(a,type='l',ylim=c(min(c(a,b,c)),max(c(a,b,c))))
lines(b,lty=2)
lines(c,lty=3,col='blue')

# setup for no margins on the legend
par(mar=c(0, 0, 0, 0))
# c(bottom, left, top, right)
plot.new()
legend('center','groups',c("A","B","C"), lty = c(1,2,3),
       col=c('black','black','blue'),ncol=3,bty ="n")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Pie*_*nte 25

您必须将图例框的大小添加到ylim范围

#Plot an empty graph and legend to get the size of the legend
x <-1:10
y <-11:20
plot(x,y,type="n", xaxt="n", yaxt="n")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"),plot = FALSE)

#custom ylim. Add the height of legend to upper bound of the range
my.range <- range(y)
my.range[2] <- 1.04*(my.range[2]+my.legend.size$rect$h)

#draw the plot with custom ylim
plot(x,y,ylim=my.range, type="l")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 使用`legend(...,plot = FALSE)`的+1,因为这正是进行所需计算所需要的.我昨天玩弄了这个,但没有把它作为答案发布,因为我认为第一个插件是一个丑陋的,但不幸的是一个必不可少的要求,以便`legend()`返回有用单位的尺寸,用于想要添加的情节传说也是.耻辱`legend()`需要一个情节才能做到这一点 - 我们不能在[0,1]单位工作并在以后扩展吗? (2认同)

Gee*_*cid 10

在@ P-Lapointe解决方案的基础上,使其非常简单,您可以使用数据中的最大值max(),然后重新使用这些最大值来设置legendxy坐标.为确保不超出边界,请ylim略微设置最大值.

a=c(rnorm(1000))
b=c(rnorm(1000))
par(mfrow=c(1,2))
plot(a,ylim=c(0,max(a)+1))
legend(x=max(a)+0.5,legend="a",pch=1)
plot(a,b,ylim=c(0,max(b)+1),pch=2)
legend(x=max(b)-1.5,y=max(b)+1,legend="b",pch=2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述