Skip to content

Commit 2e15938

Browse files
committed
Use grobWidth instead of stringWidth when calculating legend sizes
1 parent b25b52b commit 2e15938

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

NEWS

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,5 @@ ggplot2 0.8.5 (2009-XX-XX) ----------------------------------------
3636
have formatter argument to match scale_continuous
3737
* legends will only merge if both the title and all labels are the same.
3838
(Fixes #16)
39-
* Fix for bug #19: Legend with three constraints doesn't work
39+
* Fix for bug #19: Legend with three constraints doesn't work
40+
* Legend: correctly calculate label widths for all font sizes. (Fixes #38)

R/guides-legend.r

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,17 @@ build_legend <- function(name, mapping, layers, default_mapping, theme) {
9999
nkeys <- nrow(mapping)
100100
hgap <- vgap <- unit(0.3, "lines")
101101

102-
label_width <- max(stringWidth(mapping$.label))
102+
numeric_labels <- all(sapply(mapping$.labels, is.language)) || suppressWarnings(all(!is.na(sapply(mapping$.labels, "as.numeric"))))
103+
hpos <- numeric_labels * 1
104+
105+
labels <- lapply(mapping$.label, function(label) {
106+
theme_render(theme, "legend.text", label, hjust = hpos, x = hpos, y = 0.5)
107+
})
108+
109+
label_width <- do.call("max", lapply(labels, grobWidth))
110+
label_width <- convertWidth(label_width, "cm")
111+
label_heights <- do.call("unit.c", lapply(labels, grobHeight))
112+
label_heights <- convertHeight(label_heights, "cm")
103113

104114
width <- max(unlist(llply(legend_data, "[[", "size")), 0)
105115
key_width <- max(theme$legend.key.size, unit(width, "mm"))
@@ -112,20 +122,20 @@ build_legend <- function(name, mapping, layers, default_mapping, theme) {
112122
hgap
113123
)
114124
)
115-
116-
label.heights <- stringHeight(mapping$.label)
125+
widths <- convertWidth(widths, "cm")
117126

118127
heights <- unit.c(
119128
vgap,
120129
unit(1, "grobheight", title),
121130
vgap,
122131
unit.pmax(
123132
theme$legend.key.size,
124-
label.heights,
133+
label_heights,
125134
unit(key_heights, "mm")
126135
),
127136
vgap
128137
)
138+
heights <- convertHeight(heights, "cm")
129139

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

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

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

0 commit comments

Comments
 (0)