# r - 在基本图形中绘制绘图区域外的图例？

``````# Random data to plot:
A <- data.frame(x=rnorm(100, 20, 2), y=rnorm(100, 20, 2))
B <- data.frame(x=rnorm(100, 21, 1), y=rnorm(100, 21, 1))

# Add extra space to right of plot area; change clipping to figure
par(mar=c(5.1, 4.1, 4.1, 8.1), xpd=TRUE)

# Plot both groups
plot(y ~ x, A, ylim=range(c(A\$y, B\$y)), xlim=range(c(A\$x, B\$x)), pch=1,
main="Scatter plot of two groups")
points(y ~ x, B, pch=3)

# Add legend to top right, outside plot region
legend("topright", inset=c(-0.2,0), legend=c("A","B"), pch=c(1,3), title="Group")
``````

`inset=c(-0.2,0)`的第一个值可能需要根据图例的宽度进行调整。

Question

``````plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
legend(1,-1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))
``````

``````# Expand right side of clipping rect to make room for the legend
par(xpd=T, mar=par()\$mar+c(0,0,0,6))

# Plot graph normally
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")

# Plot legend where you want
legend(3.2,1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

# Restore default clipping rect
par(mar=c(5, 4, 4, 2) + 0.1)
``````

``````par(xpd=T, mar=par()\$mar+c(0,0,0,5))
``````

``````plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
``````

``````legend(locator(1),c("group A", "group B"), pch = c(1,2), lty = c(1,2))
``````

``````x = c(0,1,2,3,4,5,6,7,8)
y = c(0,3,6,4,5,2,3,5,4)
x2 = c(0,1,2,3,4,5,6,7,8)
y2 = c(0,4,7,8,3,6,3,3,4)
``````

``````legendstyle = list("x"=100, "y"=1)
layoutstyle = list(legend=legendstyle)
``````

• 右边底部的`list("x" = 100, "y" = 0)`
• `list("x" = 100, "y"= 1)`右上方
• `list("x" = 100, "y" = .5)`在右边中间
• `list("x" = 0, "y" = -100)`在Left下
• `list("x" = 0.5, "y" = -100)`在中心下
• `list("x" = 1, "y" = -100)`在右下

`response = p\$plotly(x,y,x2,y2, kwargs=list(layout=layoutstyle));`

``````url = response\$url
filename = response\$filename
``````

``````plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
``````

``````legend("bottomright", c("group A", "group B"), pch=c(1,2), lty=c(1,2),
inset=c(0,1), xpd=TRUE, horiz=TRUE, bty="n"
)
``````

• `inset=c(0,1)` - 将图例按（x，y）方向的绘图区域分数移动。 在这种情况下，图例处于`"bottomright"`位置。 它由x方向上的0个绘制区域（因此保持在“右”）和1个y方向上的绘制区域（从下到上）移动。 它恰好位于情节之上。
• `xpd=TRUE` - 让图例出现在绘图区域之外。
• `horiz=TRUE` - 指示产生一个水平图例。
• `bty="n"` - 摆脱传说边框的风格细节。

``````par(mar=c(5,4,2,6))
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")

legend("topleft", c("group A", "group B"), pch=c(1,2), lty=c(1,2),
inset=c(1,0), xpd=TRUE, bty="n"
)
``````

### Tags

r   plot   legend