Open AlsoATraveler opened 3 years ago
There is a command add.legend
.
E.g. from the help file
library(ggplot2)
library(gg.gap)
mtcars$gear <- factor(mtcars$gear)
bp <- ggplot(data = mtcars, aes(x = gear, fill = gear)) +
geom_bar() +
ggtitle("Number of Cars by Gear") +
xlab("Gears")
gg.gap(plot = bp,
ylim = c(0,16),
segments = c(6,8))
add.legend(plot = bp,
margin = c(top=1,right=1,bottom=1,left=460))
It seems like you can only do one or the other--either gg.gap or add.legend. It never lets me save both the gap plot with the legend on it to one plot.
there is a warning for add.legend
Warning message:
In get_plot_component(plot, "guide-box") :
Multiple components found; returning the first one. To return all, use return_all = TRUE
.
may help
# I found that the error in the add.legend function comes from cowplot::get_plot_component.
# However, theoretically, this error has nothing to do with the code execution.
# Nevertheless, this error also indicates that there is an issue with the number of legend components extracted.
# The code extracted empty legend components, null.
# Thus, it drew a blank legend.
# I deconstructed the add.legend function into its original functions
# and added a manual step to select the legend.
# This resolved the issue.
# However, the cause of the problem remains unclear.
# It's probably a ggplot2 issue.
# Plotting
p1 <- ggplot(...) +
theme(legend.position = c(0.8, 0.8))
# Extracting legend components
library(cowplot)
legend <- get_plot_component(p1, "guide-box", return_all = TRUE)
# Here's the key to solving the problem
legend <- legend[[?]] # Please select the legend you need from the previous result
# Setting breaks on the Y-axis
p1 <- gg.gap(plot = p1,
segments = c(2,4),
tick_width = c(1,2),
rel_heights = c(1,0,0.5),
ylim = c(0,8))
# Plot to the output frame
p1
# Drawing the extracted legend
library(grid)
grid.draw(legend)
Hi,the legend disappeared after I used gg.gap to draw,what should I do?