Reputation: 457
I want to have two plots next to each other and a common legend for both.
Like This:
Plot 1 | Plot 2 | Legend
Unfortunately, the legend is plotted inside of the second plot...
This is my current approach:
par(mfrow=c(1,3))
plot(...)
plot.new()
plot(...)
legend("center", ...)
I thought with par(mfrow=c(1,3)) I would get one row with 3 columns of plots - so exactely the result I wanted to obtain. Is the legend maybe not treated as a plot but as belonging to plot number 2 and so it is plotted with the same column?
Upvotes: 1
Views: 191
Reputation: 73262
You were close. legend
needs a plot.new
in front of it, if you want to have it as a "standalone" plot.
par(mfrow=c(1, 3))
plot(1:10)
plot(1:10)
plot.new()
legend("center", pch=1, legend=c("x", "y"))
Upvotes: 1
Reputation: 2829
I hope this works for you as an example. Nevertheless, there are better libraries to be used such as ggplot2
or plotly
.
par(mfrow = c(1, 2), oma = c(0, 0, 0, 2))
plot(hp~mpg, data=mtcars, col=cyl,pch=19)
plot(disp~wt, data=mtcars, col=cyl,pch=19)
legend(x=6, y=250, legend=as.numeric(levels(factor(mtcars$cyl))), pch=19, col= as.numeric(levels(factor(mtcars$cyl))) )
Upvotes: 0