Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to adjust legend in a row in R?

Tags:

plot

r

legend

I have one plot and i need to adjust legends in a row. How can i do it?

plot(x,y)
legend(c("x","y"))

I need legend should be in one line

    ----- x                 --------- y 

Regards

like image 893
Manish Avatar asked Oct 04 '22 04:10

Manish


1 Answers

You want to set horiz=TRUE in legend. Here's a comparison of the default behavior (horiz=FALSE) to horiz=TRUE.

enter image description here

This plot is based on the second example from the legend documentation:

layout(matrix(1:2,nrow=1))
# `horiz=FALSE` (default behavior)
plot(x, sin(x), type = "l", ylim = c(-1.2, 1.8), col = 3, lty = 2, main="horiz=FALSE (Default)")
points(x, cos(x), pch = 3, col = 4)
lines(x, tan(x), type = "b", lty = 1, pch = 4, col = 6)
legend(-1, 1.9, c("sin", "cos", "tan"), col = c(3, 4, 6),
       text.col = "green4", lty = c(2, -1, 1), pch = c(NA, 3, 4),
       merge = TRUE, bg = "gray90")
# `horiz=TRUE`
plot(x, sin(x), type = "l", ylim = c(-1.2, 1.8), col = 3, lty = 2, main="horiz=TRUE")
points(x, cos(x), pch = 3, col = 4)
lines(x, tan(x), type = "b", lty = 1, pch = 4, col = 6)
legend(-1, 1.9, c("sin", "cos", "tan"), col = c(3, 4, 6),
       text.col = "green4", lty = c(2, -1, 1), pch = c(NA, 3, 4),
       merge = TRUE, bg = "gray90", horiz=TRUE)
like image 61
Thomas Avatar answered Oct 07 '22 18:10

Thomas