我希望将不同函数生成的多个图表组合到一个显示中。具体来说,我只想保留第一个图表的图例。
这是问题的最小版本:
library(ggplot2)
library(patchwork)
plot_histogram <- function() {
plot_data <- ggplot(mtcars, aes(x = mpg, fill = factor(am))) +
geom_histogram(binwidth = 2, color = "black") +
labs(title = "Histo",
x = "Miles/gallon",
y = "nb cars",
fill = "Transmission") +
scale_fill_manual(values = c("skyblue", "salmon"), labels = c("Auto", "Man")) +
theme_minimal() +
theme(legend.position = "bottom")
return(plot_data)
}
plot_scatter <- function() {
plot_data <- ggplot(mtcars, aes(x = mpg, y = wt, color = factor(cyl))) +
geom_point(size = 3) +
labs(title = "Scatterplot",
x = "Miles/gallon",
y = "weight",
color = "Cyl") +
theme_minimal() +
theme(legend.position = "bottom")
return(plot_data)
}
scatter_plot_left <- plot_scatter()
scatter_plot_right <- plot_scatter()
histogram_plot <- plot_histogram()
combined_plots <- wrap_plots(scatter_plot_left + scatter_plot_right,
histogram_plot,
nrow = 1,
widths = c(3, 1)) +
plot_layout(guides = 'collect') &
theme(legend.position = "bottom")
combined_plots
有没有办法只保留散点图的图例?
从现在开始,我发现的最好的“解决方案”是用
guides = 'collect'
包裹前两个图表,然后用另一个图表包裹它而不保留图例。
这并不是一个真正的解决方案,因为图例不居中,您必须每次都调整图形的大小,这在自动生产过程中并不好。
提前谢谢您。
你可以像这样在函数中将
legend.position
作为参数吗?
library(ggplot2)
library(patchwork)
plot_histogram <- function(x) {
ggplot(mtcars, aes(x = mpg, fill = factor(am))) +
geom_histogram(binwidth = 2, color = "black") +
labs(
title = "Histo",
x = "Miles/gallon",
y = "nb cars",
fill = "Transmission"
) +
scale_fill_manual(values = c("skyblue", "salmon"), labels = c("Auto", "Man")) +
theme_minimal() +
theme(legend.position = x)
}
plot_scatter <- function(x) {
ggplot(mtcars, aes(x = mpg, y = wt, color = factor(cyl))) +
geom_point(size = 3) +
labs(
title = "Scatterplot",
x = "Miles/gallon",
y = "weight",
color = "Cyl"
) +
theme_minimal() +
theme(legend.position = x)
}
scatter_plot_left <- plot_scatter("none")
scatter_plot_right <- plot_scatter("bottom")
histogram_plot <- plot_histogram("none")
wrap_plots(scatter_plot_left + scatter_plot_right,
histogram_plot,
nrow = 1,
widths = c(3, 1)
)
创建于 2024-05-03,使用 reprex v2.1.0