如何在 r 中的绘图之外绘制图例
在基本 R 图之外绘制图例的最简单方法是使用以下语法在图右侧添加额外的空间:
by( mar =c(5, 4, 4, 8), xpd= TRUE )
以下分步示例展示了如何在实践中使用此语法。
第 1 步:创建数据
首先,让我们创建一些要使用的数据:
#create data frames df1 <- data. frame (x=c(1, 2, 3, 4, 5, 6, 7), y=c(2, 7, 19, 26, 24, 29, 31)) df2 <- data. frame (x=c(1, 2, 3, 4, 5, 6, 7), y=c(4, 4, 7, 9, 12, 13, 8))
步骤 2:创建一个绘图,并在绘图外添加图例
接下来,我们创建一个路径,并在右上角的路径外添加图例:
#add extra space to the right of the plot
by( mar =c(5, 4, 4, 8), xpd= TRUE )
#plot both data frames
plot(y ~ x, df1, pch =1, main=" Scatterplot with multiple groups ")
points(y ~ x, df2, pch =3)
#add legend outside of plot
legend(" topright ", inset =c(-0.2, 0), legend =c(" df1 "," df2 "), pch =c(1,3), title =" Data ")
第 3 步:更改图例位置
inset(x, y)参数可用于控制图例右侧图例的位置。例如,我们可以使参数x更负,以将图例进一步向右推:
#add extra space to the right of the plot
by( mar =c(5, 4, 4, 8), xpd= TRUE )
#plot both data frames
plot(y ~ x, df1, pch =1, main=" Scatterplot with multiple groups ")
points(y ~ x, df2, pch =3)
#add legend outside of plot
legend(" topright ", inset =c(-0.3, 0), legend =c(" df1 "," df2 "), pch =c(1,3), title =" Data ")
我们还可以使y参数变得更积极,以将图例推低:
#add extra space to the right of the plot
by( mar =c(5, 4, 4, 8), xpd= TRUE )
#plot both data frames
plot(y ~ x, df1, pch =1, main=" Scatterplot with multiple groups ")
points(y ~ x, df2, pch =3)
#add legend outside of plot
legend(" topright ", inset =c(-0.3, .5), legend =c(" df1 "," df2 "), pch =c(1,3), title =" Data ")
请随意修改inset(x, y)参数的值来更改图例的位置。
您可以在此页面上找到更多 R 教程。