Home > database >  How to fix "Breaks and labels are different lengths" when using ggplot2 for faceted plots?
How to fix "Breaks and labels are different lengths" when using ggplot2 for faceted plots?

Time:03-04

Consider the following example:

library(ggplot2)
library(RColorBrewer)
library(magrittr)
library(dplyr)

df <- data.frame(x = seq(0, 70, 0.5),
                 y = seq(0, 70, 0.5),
                 val = rnorm(141),
                 group =rep(1:3,47))

max_val_plot <- df$val %>%  max() %>% round(0)
min_val_plot <--df$val %>%  min() %>% round(0)

breaks_plot <-seq(min_val_plot,max_val_plot,0.1) 

n <- breaks_plot %>%  length()

getPalette <- colorRampPalette(brewer.pal(9, "RdBu"))

colors_plot <-getPalette(n)

labels_plot <- breaks_plot %>%
  as.character() 
labels_plot[!1:0]=' '

df %>%  
  ungroup() %>% 
  ggplot(aes(x=x,y=y,fill=val)) 
  geom_raster() 
  facet_grid(~group) 
  theme_bw(base_size = 20) 
  scale_fill_stepsn(
    name = "",
    colours = colors_plot,
    breaks = breaks_plot,
    labels = labels_plot
  ) 

Although labels and breaks are of equal length, the error "Breaks and labels are different lengths" is returned due to the presence of multiple groups and the faceted function in plotting code.

How can I fix this?

Thanks!

CodePudding user response:

One option to fix your issue would be to pass a function to the labels argument of scale_fill_xxx to create the labels on the fly instead of providing the labels as a vector.

library(ggplot2)
library(RColorBrewer)
library(magrittr)
library(dplyr)

set.seed(123)

df %>%
  ungroup() %>%
  ggplot(aes(x = x, y = y, fill = val))  
  geom_raster()  
  facet_grid(~group)  
  theme_bw(base_size = 20)  
  scale_fill_stepsn(
    name = "",
    colours = colors_plot,
    breaks = breaks_plot,
    labels = function(x) { x <- as.character(x); x[!1:0] <- " "; x}
  )

  • Related