[R] Patch for legend.position={left,top,bottom} in ggplot2
Karsten Loesing
karsten.loesing at gmx.net
Mon Jun 7 15:39:46 CEST 2010
Hi Hadley and everyone,
here's a patch for ggplot2 that fixes the behavior of
opts(legend.position={left,top,bottom}). If you try the following code
in an unmodified ggplot2
options(warn = -1)
suppressPackageStartupMessages(library("ggplot2"))
data <- data.frame(
x = c(1, 2, 3, 4, 5, 6),
y = c(2, 3, 4, 3, 4, 5),
colour = c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE))
ggplot(data, aes(x = x, y = y, colour = colour)) +
geom_line() + opts(title = "title", legend.position = "right")
ggplot(data, aes(x = x, y = y, colour = colour)) +
geom_line() + opts(title = "title", legend.position = "left")
ggplot(data, aes(x = x, y = y, colour = colour)) +
geom_line() + opts(title = "title", legend.position = "top")
ggplot(data, aes(x = x, y = y, colour = colour)) +
geom_line() + opts(title = "title", legend.position = "bottom")
you'll see that plots 2 to 4 are broken.
I think I located the bug in surround_viewports() where the graphical
elements are placed into the grid. If we increment all rows and columns
of the graphical elements for positions "left", "top", and "bottom" by
1, those graphs look sane again. I assume that a new first row and
column were added at some point in the development, but only the
parameters for the default position "right" were adjusted. Here's the patch:
--- ggplot2-orig2 2010-06-07 13:14:35.000000000 +0200
+++ ggplot2 2010-06-07 15:22:33.000000000 +0200
@@ -7003,27 +7003,27 @@
)
} else if (position == "left") {
viewports <- vpList(
- vp("panels", 2, 3),
- vp("legend_box", 2, 1),
- vp("ylabel", 2, 2),
- vp("xlabel", 3, 3),
- vp("title", 1, 3)
+ vp("panels", 3, 4),
+ vp("legend_box", 3, 2),
+ vp("ylabel", 3, 3),
+ vp("xlabel", 4, 4),
+ vp("title", 2, 4)
)
} else if (position == "top") {
viewports <- vpList(
- vp("panels", 3, 2),
- vp("legend_box", 2, 2),
- vp("ylabel", 3, 1),
- vp("xlabel", 4, 2),
- vp("title", 1, 2)
+ vp("panels", 4, 3),
+ vp("legend_box", 3, 3),
+ vp("ylabel", 4, 2),
+ vp("xlabel", 5, 3),
+ vp("title", 2, 3)
)
} else if (position == "bottom") {
viewports <- vpList(
- vp("panels", 2, 2),
- vp("legend_box", 4, 2),
- vp("ylabel", 2, 1),
- vp("xlabel", 3, 2),
- vp("title", 1, 2)
+ vp("panels", 3, 3),
+ vp("legend_box", 5, 3),
+ vp("ylabel", 3, 2),
+ vp("xlabel", 4, 3),
+ vp("title", 2, 3)
)
} else {
viewports <- vpList(
Best,
--Karsten
More information about the R-help
mailing list