我在 R 中有以下数据:
library(ggplot2)
library(dplyr)
set.seed(123)
data <- data.frame(
height = rnorm(1000, mean = 170, sd = 10),
weight = rnorm(1000, mean = 70, sd = 15),
country = sample(c("USA", "Canada", "UK", "Australia"), 1000, replace = TRUE)
)
我使用这段代码来为每个国家/地区制作身高与体重的方面:
library(ggplot2)
library(gridExtra)
# Create separate plots for each country
p1 <- ggplot(data %>% filter(country == "USA"), aes(x = height, y = weight)) +
geom_point(alpha = 0.5) +
labs(title = "USA", x = "Height (cm)", y = "Weight (kg)") +
theme_minimal()
p2 <- ggplot(data %>% filter(country == "Canada"), aes(x = height, y = weight)) +
geom_point(alpha = 0.5) +
labs(title = "Canada", x = "Height (cm)", y = "Weight (kg)") +
theme_minimal()
p3 <- ggplot(data %>% filter(country == "UK"), aes(x = height, y = weight)) +
geom_point(alpha = 0.5) +
labs(title = "UK", x = "Height (cm)", y = "Weight (kg)") +
theme_minimal()
p4 <- ggplot(data %>% filter(country == "Australia"), aes(x = height, y = weight)) +
geom_point(alpha = 0.5) +
labs(title = "Australia", x = "Height (cm)", y = "Weight (kg)") +
theme_minimal()
grid.arrange(p1, p2, p3, p4, ncol = 2)
R 中是否有一些功能可以让我不用手动制作所有这些图表,而是可以自动制作具有正确标题的每个图表并将它们平铺在同一页面上?
现在我正在手动执行此操作,这需要一些时间(例如,我有 20 个这样的图表) - 难道不能自动执行此操作吗?
如果您不想要方面,那么只需编写自己的绘图函数并将其应用于数据即可。例如:
这是概括性的;任何时候你发现自己编写了大量非常相似的代码,你就应该应用一个函数来代替。