set.seed
(5642)
sample_data <-
data.frame
(
name =
c
(
"Geek1"
,
"Geek2"
,
"Geek3"
,
"Geek4"
,
"Geeek5"
) ,
value=
c
(31,12,15,28,45))
library
(
"ggplot2"
)
library
(
"gridExtra"
)
plot1<-
ggplot
(sample_data,
aes
(x = name, y = value, col=name)) +
geom_point
(size=4)+
theme
(legend.position =
"none"
)
plot2<-
ggplot
(sample_data,
aes
(x = name, y = value, fill=name)) +
geom_col
()+
theme
(legend.position =
"none"
)
combined_plot <-
grid.arrange
(plot1, plot2, ncol = 2)
plot1_legend <-
ggplot
(sample_data,
aes
(x = name, y = value, col=name)) +
geom_point
(size=4)+
theme
(legend.position =
"bottom"
)
get_only_legend <-
function
(plot) {
plot_table <-
ggplot_gtable
(
ggplot_build
(plot))
legend_plot <-
which
(
sapply
(plot_table$grobs,
function
(x) x$name) ==
"guide-box"
)
legend <- plot_table$grobs[[legend_plot]]
return
(legend)
}
legend <-
get_only_legend
(plot1_legend)
grid.arrange
(combined_plot, legend, nrow = 2, heights =
c
(10, 1))