r - How can I make the legend in ggplot2 the same height as my plot? -
i have generated simple plot in r (version r version 3.0.1 (2013-05-16)) using ggplot2
(version 0.9.3.1) shows correlation coefficients set of data. currently, legend colorbar on right side of plot fraction of entire plot size.
i legend colorbar same height plot. thought use legend.key.height
this, have found not case. investigated grid
package unit
function , found there normalized units in there when tried them (unit(1, "npc")
), colorbar way tall , went off page.
how can make legend same height plot itself?
a full self contained example below:
# load needed libraries library(ggplot2) library(grid) library(scales) library(reshape2) # generate collection of sample data variables = c("var1", "var2", "var3") data = matrix(runif(9, -1, 1), 3, 3) diag(data) = 1 colnames(data) = variables rownames(data) = variables # generate plot corrs = data ggplot(melt(corrs), aes(x = var1, y = var2, fill = value)) + geom_tile() + geom_text(parse = true, aes(label = sprintf("%.2f", value)), size = 3, color = "white") + theme_bw() + theme(panel.border = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1), aspect.ratio = 1, legend.position = "right", legend.key.height = unit(1, "inch")) + labs(x = "", y = "", fill = "", title = "correlation coefficients") + scale_fill_gradient2(limits = c(-1, 1), expand = c(0, 0), low = muted("red"), mid = "black", high = muted("blue"))
it seems quite tricky, closest got this,
## panel height 1null, work out subtracting other heights 1npc ## , 1line default plot margins panel_height = unit(1,"npc") - sum(ggplotgrob(plot)[["heights"]][-3]) - unit(1,"line") plot + guides(fill= guide_colorbar(barheight=panel_height))
unfortunately vertical justification bit off.
Comments
Post a Comment