如何在R的ggplot2绘图左侧加文本框、右侧加水平直方图?
实现带统计文本框和右侧水平直方图的散点图
要完成需求,我们可以用ggplot2绘制各部分图形,再通过patchwork包拼接布局,步骤如下:
- 计算hwy列的统计量
先算出hwy列的均值和标准差,用于左侧文本框:
# 计算hwy的均值与标准差 hwy_stats <- data.frame( mean = round(mean(mpg$hwy), 2), sigma = round(sd(mpg$hwy), 2) )
- 绘制左侧统计文本框
用空的ggplot生成仅包含统计文本的图形,去掉多余绘图元素:
# 左侧统计文本框 text_plot <- ggplot() + annotate("text", x = 1, y = 1, label = paste0("mean = ", hwy_stats$mean, "\nsigma = ", hwy_stats$sigma), size = 5) + theme_void()
- 绘制中间散点图
基于你提供的代码优化,调整边距方便后续拼接:
# 核心散点图 scatter_plot <- ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() + theme(plot.margin = margin(5, 5, 5, 5))
- 绘制右侧水平直方图
将直方图转为水平方向,隐藏重复的y轴元素:
# 右侧水平直方图 hist_plot <- ggplot(mpg, aes(x = hwy)) + geom_histogram(bins = 15, fill = "lightblue", color = "black") + coord_flip() + theme_minimal() + theme(axis.title.y = element_blank(), axis.text.y = element_blank(), plot.margin = margin(5, 5, 5, 5))
- 拼接所有图形
用patchwork组合三个图形,设置合适的宽度比例:
# 安装并加载patchwork包(如果未安装) if (!require(patchwork)) { install.packages("patchwork") library(patchwork) } # 拼接布局,调整各部分宽度占比 combined_plot <- text_plot + scatter_plot + hist_plot + plot_layout(widths = c(1, 4, 1)) # 展示最终图形 print(combined_plot)
内容的提问来源于stack exchange,提问作者samir
相关产品推荐
相关产品推荐

