Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set standard legend key size with long label names ggplot

Tags:

r

legend

ggplot2

I am building a ggplot visualization in which some fill aesthetics have very long variable names, while other variable names are short. Adding long names changes the size of the legend key corresponding to the long text - lengthening it to match the text. I am wondering if there is a way to standardize the legend key height across all varibles, and change the spaces between the legend items.

I tried modifying theme(legend.key.height()) and theme(legend.key.width()) but that didn't solve the problem.

Here is example code:

#load neccesary package
library('ggplot2')

#create the dataframe
df <- data.frame(year = as.integer(c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2)),
                 class = c('A', 'B', 'C', 'D', 'E'), 
                 value = c(50, 50))

#Create plot
g <- ggplot(df, aes(x = year, y = value, fill = class)) + 
  geom_col(position = 'stack') + 
  scale_fill_discrete(labels = c('This is an\nextremely\nlong label\nname', 'short label1', 'Another\nlong\nlabel\nname', 'short label3', 'short label4'))

Plots:

enter image description here

What I want is to have the same key size for all variables, with the white space between keys changing to accommodate the long text. So something that looks like this:

enter image description here

Trying g + theme(legend.key.height = unit(3, 'mm'), legend.key.width = unit(3, 'mm'))

Does not resolve the problem.

Any thoughts?

like image 873
MorrisseyJ Avatar asked Jan 20 '21 15:01

MorrisseyJ


People also ask

How do I change the size of a legend key in R?

To change the Size of Legend, we have to add guides() and guide_legend() functions to the geom_point() function. Inside guides() function, we take parameter color, which calls guide_legend() guide function as value.

How do I change the legend label in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I change labels in legend?

Click on the legend name you want to change in the Select Data Source dialog box, and click Edit. Note: You can update Legend Entries and Axis Label names from this view, and multiple Edit options might be available.

How do I make my legend box smaller in ggplot2?

To specify the legend box size you could use + theme(legend. key. size = unit(2, "cm")) .

How to change Legend labels in ggplot2?

How to Change Legend Labels in ggplot2 (With Examples) You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete (labels=c ('label1', 'label2', 'label3',...)) The following example shows how to use this syntax in practice.

How to change the size of legend in Python Geom_point?

Let us first create a regular plot without any modifications so that the difference is apparent. To change the Size of Legend, we have to add guides () and guide_legend () functions to the geom_point () function. Inside guides () function, we take parameter color, which calls guide_legend () guide function as value.

How to change the color of the labels of a legend?

Other option is passing the new labels to the labels argument of the scale_color_hue or scale_fill_hue functions to modify only the labels or using scale_color_discrete or scale_fill_discrete functions if you also want to change the colors. In case you want to reorder the labels of the legend you will need to reorder the factor variable.

How do I change the Order of Legends in an R plot?

R function: guides () Change the legend order in the situation where you have multiple legends (or multiple guides) generated by using multiple aesthetics (shape, color, size, fill, etc) in the plot. For example, you might have one legend for point shape and another for point color and size.


Video Answer


1 Answers

An alternative to making a custom guide is to make a custom drawing function for the legend glyphs. The change relative to draw_key_polygon() is that the width and height are set to "snpc" units instead of "npc" units.

#load neccesary package
library(ggplot2)
library(grid)
library(rlang)

draw_square <- function(data, params, size) {
  if (is.null(data$size)) {
    data$size <- 0.5
  }
  lwd <- min(data$size, min(size) /4)
  grid::rectGrob(
    width  = unit(1, "snpc") - unit(lwd, "mm"),
    height = unit(1, "snpc") - unit(lwd, "mm"),
    gp = gpar(
      col = data$colour %||% NA,
      fill = alpha(data$fill %||% "grey20", data$alpha),
      lty = data$linetype %||% 1,
      lwd = lwd * .pt,
      linejoin = params$linejoin %||% "mitre",
      lineend = if (identical(params$linejoin, "round")) "round" else "square"
    )
  )
}

#create the dataframe
df <- data.frame(year = as.integer(c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2)),
                 class = c('A', 'B', 'C', 'D', 'E'), 
                 value = c(50, 50))

#Create plot
g <- ggplot(df, aes(x = year, y = value, fill = class)) + 
  geom_col(position = 'stack', key_glyph = draw_square) + 
  scale_fill_discrete(labels = c('This is an\nextremely\nlong label\nname', 'short label1', 'Another\nlong\nlabel\nname', 'short label3', 'short label4'))
g

Created on 2021-08-19 by the reprex package (v1.0.0)

like image 113
teunbrand Avatar answered Nov 15 '22 07:11

teunbrand