gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
我想在r语言中用ggplot2,画图,想把两幅图组合在一起共用纵坐标,代码应该怎么改?
- User
我想在r语言中用ggplot2,画图,想把两幅图组合在一起共用纵坐标,代码应该怎么改?
- Assistant
在 R 语言中使用
ggplot2来组合两幅图,可以使用patchwork包或gridExtra包。这里介绍两种方法:方法 1: 使用
patchwork包首先,你需要安装并加载
patchwork包(如果还没有安装的话):install.packages("patchwork") library(ggplot2) library(patchwork)然后,你可以创建两个 ggplot 对象,并用
+将它们组合在一起。例如:# 创建第一幅图 plot1 <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + labs(title = "图1: Weight vs MPG") # 创建第二幅图 plot2 <- ggplot(mtcars, aes(x = wt, y = hp)) + geom_point() + labs(title = "图2: Weight vs HP") # 组合两幅图 combined_plot <- plot1 / plot2 + plot_layout(heights = c(1, 1)) # / 表示上下排列 combined_plot方法 2: 使用
gridExtra包同样地,首先安装并加载
gridExtra包(如果还没有安装的话):install.packages("gridExtra") library(ggplot2) library(gridExtra)然后,创建两个 ggplot 对象并用
grid.arrange()来组合它们:# 创建第一幅图 plot1 <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + labs(title = "图1: Weight vs MPG") # 创建第二幅图 plot2 <- ggplot(mtcars, aes(x = wt, y = hp)) + geom_point() + labs(title = "图2: Weight vs HP") # 组合两幅图 grid.arrange(plot1, plot2, ncol = 1) # ncol = 1表示一列,堆叠显示