Skip to content

Commit

Permalink
Use grobWidth instead of stringWidth when calculating legend sizes
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Dec 10, 2009
1 parent b25b52b commit 2e15938
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
3 changes: 2 additions & 1 deletion NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,5 @@ ggplot2 0.8.5 (2009-XX-XX) ----------------------------------------
have formatter argument to match scale_continuous
* legends will only merge if both the title and all labels are the same.
(Fixes #16)
* Fix for bug #19: Legend with three constraints doesn't work
* Fix for bug #19: Legend with three constraints doesn't work
* Legend: correctly calculate label widths for all font sizes. (Fixes #38)
20 changes: 14 additions & 6 deletions R/guides-legend.r
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,17 @@ build_legend <- function(name, mapping, layers, default_mapping, theme) {
nkeys <- nrow(mapping)
hgap <- vgap <- unit(0.3, "lines")

label_width <- max(stringWidth(mapping$.label))
numeric_labels <- all(sapply(mapping$.labels, is.language)) || suppressWarnings(all(!is.na(sapply(mapping$.labels, "as.numeric"))))
hpos <- numeric_labels * 1

labels <- lapply(mapping$.label, function(label) {
theme_render(theme, "legend.text", label, hjust = hpos, x = hpos, y = 0.5)
})

label_width <- do.call("max", lapply(labels, grobWidth))
label_width <- convertWidth(label_width, "cm")
label_heights <- do.call("unit.c", lapply(labels, grobHeight))
label_heights <- convertHeight(label_heights, "cm")

width <- max(unlist(llply(legend_data, "[[", "size")), 0)
key_width <- max(theme$legend.key.size, unit(width, "mm"))
Expand All @@ -112,20 +122,20 @@ build_legend <- function(name, mapping, layers, default_mapping, theme) {
hgap
)
)

label.heights <- stringHeight(mapping$.label)
widths <- convertWidth(widths, "cm")

heights <- unit.c(
vgap,
unit(1, "grobheight", title),
vgap,
unit.pmax(
theme$legend.key.size,
label.heights,
label_heights,
unit(key_heights, "mm")
),
vgap
)
heights <- convertHeight(heights, "cm")

# Layout the legend table
legend.layout <- grid.layout(
Expand All @@ -136,8 +146,6 @@ build_legend <- function(name, mapping, layers, default_mapping, theme) {
fg <- ggname("legend", frameGrob(layout = legend.layout))
fg <- placeGrob(fg, theme_render(theme, "legend.background"))

numeric_labels <- all(sapply(mapping$.labels, is.language)) || suppressWarnings(all(!is.na(sapply(mapping$.labels, "as.numeric"))))
hpos <- numeric_labels * 1

fg <- placeGrob(fg, title, col = 2:4, row = 2)
for (i in 1:nkeys) {
Expand Down

0 comments on commit 2e15938

Please sign in to comment.