0

I have a data set with a big negative value, so I used gg.gap package to make a discontinuous y-axis. The code worked well but after adding the function gg.gap the legend was deleted. I tried adding a legend using the add.legend argument but it didn't work. Am I doing something wrong? Here is a sample code

df<- data.frame(
 var1 = c(3.2,5.1,-25000,3.9,4.6,3.1),
 var2 = c(2020,2021,2022,2020,2021,2022),
 var3 = c("c","c","c","t","t","t")
)

test<-ggplot(df, aes(x = as.factor(var2), y = var1, fill = var3)) +
 geom_col(position = position_dodge(width = 0.9)) +
 scale_fill_viridis_d() +  # Use the color-blind-friendly viridis palette
 labs(
  title = "Grouped Bar Plot",
  x = "Year",
  y = "Variable 1",
  fill = "Group"
 ) + 
 theme_minimal() +
 theme(legend.position = "bottom")
gg.gap(plot=test,segments=c(-24900,0),ylim= c(-25000,10))

1 Answer 1

1

From my understanding and the warning message

In get_plot_component(plot, "guide-box") : Multiple components found; returning the first one. To return all, use return_all = TRUE.

which is raised by cowplot under the hood the issue seems to be related to a recent change in the guide system of ggplot2. Additionally note that the gg.gap package is quite old and the last update stems from 2019.

Perhaps there is an option to make gg.gap work but overall I would suggest to have a look at the ggbreak package to achieve your desired result:

library(ggplot2)
library(ggbreak)
#> ggbreak v0.1.2
#> 
#> If you use ggbreak in published research, please cite the following
#> paper:
#> 
#> S Xu, M Chen, T Feng, L Zhan, L Zhou, G Yu. Use ggbreak to effectively
#> utilize plotting space to deal with large datasets and outliers.
#> Frontiers in Genetics. 2021, 12:774846. doi: 10.3389/fgene.2021.774846

df <- data.frame(
  var1 = c(3.2, 5.1, -25000, 3.9, 4.6, 3.1),
  var2 = c(2020, 2021, 2022, 2020, 2021, 2022),
  var3 = c("c", "c", "c", "t", "t", "t")
)

ggplot(df, aes(x = as.factor(var2), y = var1, fill = var3)) +
  geom_col(position = position_dodge(width = 0.9)) +
  scale_fill_viridis_d() + # Use the color-blind-friendly viridis palette
  labs(
    title = "Grouped Bar Plot",
    x = "Year",
    y = "Variable 1",
    fill = "Group"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom") +
  scale_y_break(c(-24990, -10), space = 2)

4
  • Thanks that looks great but I keep getting this error when I try to run scale_y_break Error in Ops.data.frame(guide_loc, panel_loc) : ‘==’ only defined for equally-sized data frames I will reset R and see if the error persists Commented May 21 at 16:02
  • What are your versions of ggplot2, ggbreak and R? Mine are 3.5.1, 0.1.2 and 4.3.2.
    – stefan
    Commented May 22 at 4:14
  • They are the same version. Commented May 22 at 4:57
  • 1
    Ok Thanks, it worked. I updated my R version to 4.4.0 and it worked Commented May 22 at 5:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.