# 图(a) 垂直并列条形图
p1 <- ggplot(df1, aes(x = cyl, y = 数量, fill = vs)) +
geom_col(width = 0.7, position = position_dodge(0.8), color = "black") +
scale_fill_manual(values = c("#66c2a5", "#fc8d62")) +
geom_text(aes(label = 数量),
position = position_dodge(0.8),
vjust = -0.5,
size = 4) +
labs(title = "(a) 气缸数与发动机类型(垂直并列)",
x = "气缸数",
y = "车辆数量",
fill = "发动机类型") +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5))
# 图(b) 水平并列条形图
p2 <- ggplot(df1, aes(x = cyl, y = 数量, fill = vs)) +
geom_col(width = 0.7, position = position_dodge(0.8), color = "black") +
scale_fill_manual(values = c("#66c2a5", "#fc8d62")) +
geom_text(aes(label = 数量),
position = position_dodge(0.8),
hjust = -0.2,
size = 4) +
coord_flip() +
labs(title = "(b) 气缸数与发动机类型(水平并列)",
x = "气缸数",
y = "车辆数量",
fill = "发动机类型") +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5))
# 图(c) 垂直堆叠条形图
p3 <- ggplot(df2, aes(x = cyl, y = 数量, fill = am)) +
geom_col(width = 0.7, color = "black") +
scale_fill_manual(values = c("#8da0cb", "#e78ac3")) +
geom_text(aes(label = 数量),
position = position_stack(vjust = 0.5),
size = 4) +
labs(title = "(c) 气缸数与变速器类型(垂直堆叠)",
x = "气缸数",
y = "车辆数量",
fill = "变速器类型") +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5))
# 图(d) 水平堆叠条形图
p4 <- p3 +
coord_flip() +
labs(title = "(d) 气缸数与变速器类型(水平堆叠)")
# 组合图形
grid.arrange(p1, p2, p3, p4, ncol = 2)