N'ya
N'ya

Reputation: 347

How to plot filled boxed around line and point in legend?

Some data

dummy.dt <- data.frame(c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1000))

plot(dummy.dt, type="n", xlab="x" , ylab="y", xaxt = "n", log = "y")

legend("top", inset=.02, title="legend",
       c("1", "2"), 
       pch = c(1, 1), 
       lty = c(1, 1),
       col=c("blue", "orange"),
       fill=c(rgb(red = 200, green = 200, blue = 200, maxColorValue = 255, alpha = 50), rgb(red = 100, green = 100, blue = 0, maxColorValue = 100, alpha = 50))
       )

The result looks like this:

enter image description here

The result I´d like to receive would be a filled box all around the lines. How to manipulate the size of the filled box that is created by fill?

Upvotes: 1

Views: 445

Answers (2)

Henrik
Henrik

Reputation: 67778

In the first alternative, we keep the original length of the line segments and the corresponding 'long boxes' are made from lines. Create one legend with thick lines (the 'boxes'). Add a second legend on top with the thin lines and points:

plot(1)

# "filled boxes" made of lines
legend("top", inset = 0.02, legend = 1:2, title = "legend",
       lty = 1, lwd = 10, box.col = "white",
       pch = NA,
       col = c("grey90", "yellow"))

# lines and points
legend("top", inset = 0.02, legend = 1:2, title = "legend",
       lty = 1, lwd = 1, bty = "n",
       pch = 1,
       col = c("blue", "orange"))

enter image description here

A second possibility is to decrease the length of the line segments using seg.len. Then boxes are made from points. Please note that we need to specify the same lwd and seg.len in both legend calls, i.e. also in the call for the 'boxes' where lty = 0.

plot(1)

# "filled boxes" made of points
legend("top", inset = 0.02, legend = 1:2, title = "legend",
       lty = 0, lwd = 1, seg.len = 1,
       pch = 15, pt.cex = 2,
       col = c("grey90", "yellow"))

# lines & points  
legend("top", inset = 0.02, legend = 1:2, title = "legend",
       lty = 1, lwd = 1, seg.len = 1, 
       pch = 1, bty = "n",
       col = c("blue", "orange"))

enter image description here

Upvotes: 2

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

It's not clear why you need fillat all. If you leave it out you will get only the lines plus the point character distinguished by color:

legend("top", inset=0.2, title="legend",
       c("1", "2"), 
       pch = c(1, 1), 
       lty = c(1, 1),
       col=c("blue", "orange")
   # fill=c(rgb(red = 200, green = 200, blue = 200, maxColorValue = 255, alpha = 50), 
   #        rgb(red = 100, green = 100, blue = 0, maxColorValue = 100, alpha = 50)
)

Upvotes: 0

Related Questions