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))
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)