R 绘图 - 条形图:从基础到进阶的完整指南与代码实例

📅 2026/7/19 14:58:45 👁️ 阅读次数 📝 编程学习
R 绘图 - 条形图:从基础到进阶的完整指南与代码实例

1. 引言:为什么选择条形图?

条形图(Bar Chart)是数据可视化中最基础、最直观的图表类型之一。它通过矩形条的高度或长度来展示不同类别数据的数值大小,特别适合比较离散类别之间的差异。在 R 语言中,强大的绘图系统(如基础绘图、ggplot2)让创建美观且信息丰富的条形图变得异常简单。

本文将带你从零开始,系统学习在 R 中绘制条形图的多种方法,涵盖基础绘图、ggplot2 高级定制、分组与堆叠、颜色与标签优化等核心技巧,并提供大量可直接运行的代码实例。

2. 环境准备与数据加载

在开始绘图前,我们需要准备 R 环境和示例数据。

# 安装必要的包(如果尚未安装) # install.packages("ggplot2") # install.packages("dplyr") # install.packages("reshape2") 加载库 library(ggplot2) library(dplyr) 创建示例数据集 sales_data <- data.frame( Month = c("Jan", "Feb", "Mar", "Apr", "May", "Jun"), Product_A = c(120, 150, 180, 160, 200, 220), Product_B = c(90, 110, 130, 140, 160, 180), Product_C = c(70, 85, 95, 110, 125, 140) ) 查看数据结构 print(sales_data)
# 输出结果: # Month Product_A Product_B Product_C # 1 Jan 120 90 70 # 2 Feb 150 110 85 # 3 Mar 180 130 95 # 4 Apr 160 140 110 # 5 May 200 160 125 # 6 Jun 220 180 140

3. 基础绘图系统:barplot() 函数

R 的基础绘图系统提供了简单直接的条形图绘制函数barplot()

3.1 简单垂直条形图

# 提取单列数据(Product_A 的月度销售额) product_a_sales <- sales_data$Product_A names(product_a_sales) <- sales_data$Month 绘制基础条形图 barplot(product_a_sales, main = "Product A Monthly Sales (Basic Barplot)", xlab = "Month", ylab = "Sales (Units)", col = "steelblue", border = "darkblue", ylim = c(0, 250))

3.2 水平条形图

# 绘制水平条形图 barplot(product_a_sales, horiz = TRUE, # 水平方向 main = "Product A Monthly Sales (Horizontal)", ylab = "Month", # 注意坐标轴标签交换 xlab = "Sales (Units)", col = "lightcoral", border = "darkred", xlim = c(0, 250))

3.3 添加数值标签

# 绘制条形图并保存坐标 bp <- barplot(product_a_sales, main = "Product A Sales with Value Labels", xlab = "Month", ylab = "Sales (Units)", col = "lightgreen", border = "darkgreen", ylim = c(0, 250)) 在条形顶部添加数值标签 text(x = bp, y = product_a_sales + 10, # 位置略高于条形 labels = product_a_sales, pos = 3, # 文字位置:3=上方 cex = 0.8, # 文字大小 col = "black")

4. ggplot2:优雅且强大的绘图系统

ggplot2 基于图形语法,提供了更灵活、更美观的绘图方式。

4.1 基础 ggplot2 条形图

# 准备长格式数据(ggplot2 推荐格式) library(reshape2) sales_long <- melt(sales_data, id.vars = "Month", variable.name = "Product", value.name = "Sales") 查看转换后的数据 head(sales_long)
# 绘制基础条形图(按产品分组) ggplot(sales_long, aes(x = Month, y = Sales, fill = Product)) + geom_bar(stat = "identity", position = "dodge") + # dodge 表示并列 labs(title = "Monthly Sales by Product (ggplot2)", x = "Month", y = "Sales (Units)", fill = "Product") + theme_minimal()

4.2 堆叠条形图

# 堆叠条形图展示月度总销售额构成 ggplot(sales_long, aes(x = Month, y = Sales, fill = Product)) + geom_bar(stat = "identity", position = "stack") + # stack 表示堆叠 labs(title = "Monthly Sales Composition (Stacked Bar)", x = "Month", y = "Total Sales (Units)", fill = "Product") + scale_fill_brewer(palette = "Set2") + # 使用 ColorBrewer 配色 theme_classic()

4.3 百分比堆叠条形图

# 计算每个月的百分比 sales_percent <- sales_long %>% group_by(Month) %>% mutate(Percent = Sales / sum(Sales) * 100) 绘制百分比堆叠条形图 ggplot(sales_percent, aes(x = Month, y = Percent, fill = Product)) + geom_bar(stat = "identity", position = "fill") + # fill 位置实现百分比堆叠 labs(title = "Monthly Sales Percentage (100% Stacked Bar)", x = "Month", y = "Percentage (%)", fill = "Product") + scale_fill_manual(values = c("Product_A" = "#E41A1C", "Product_B" = "#377EB8", "Product_C" = "#4DAF4A")) + # 自定义颜色 scale_y_continuous(labels = scales::percent_format()) + # Y轴显示为百分比 theme_bw()

5. 高级定制与美化技巧

5.1 调整条形宽度与间距

# 基础绘图系统调整宽度 barplot(product_a_sales, width = 0.5, # 条形宽度(默认1) space = 0.8, # 条形间距(默认0.2) main = "Adjusted Bar Width and Spacing", col = "gold", border = "orange")
# ggplot2 调整宽度 ggplot(sales_long, aes(x = Month, y = Sales, fill = Product)) + geom_bar(stat = "identity", position = position_dodge(width = 0.7), # 并列条形宽度 width = 0.6) + # 单个条形宽度 labs(title = "Customized Bar Width in ggplot2") + theme_minimal()

5.2 添加误差线(Error Bars)

# 创建带误差的数据 set.seed(123) error_data <- data.frame( Group = LETTERS[1:5], Mean = c(25, 30, 22, 35, 28), SD = c(3, 4, 2.5, 5, 3.5) # 标准差 ) 绘制带误差线的条形图 ggplot(error_data, aes(x = Group, y = Mean, fill = Group)) + geom_bar(stat = "identity", width = 0.6) + geom_errorbar(aes(ymin = Mean - SD, ymax = Mean + SD), width = 0.2, # 误差线宽度 size = 0.8, # 误差线粗细 color = "black") + labs(title = "Bar Chart with Error Bars", x = "Group", y = "Mean Value") + theme_minimal() + theme(legend.position = "none") # 隐藏图例

5.3 坐标轴标签旋转与格式化

# 长类别名称的示例 long_names <- data.frame( Category = c("Very Long Category Name A", "Extremely Long Category Name B", "Another Long Category Name C", "Short Name D"), Value = c(45, 68, 32, 89) ) ggplot(long_names, aes(x = Category, y = Value)) + geom_bar(stat = "identity", fill = "skyblue") + labs(title = "Bar Chart with Rotated X-axis Labels") + theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 旋转45度

6. 实战案例:销售数据可视化仪表板

# 案例:创建多面板销售仪表板 library(gridExtra) 图1:月度总销售额趋势 plot1 <- ggplot(sales_long %>% group_by(Month) %>% summarise(Total = sum(Sales)), aes(x = Month, y = Total)) + geom_bar(stat = "identity", fill = "#2E86AB") + geom_text(aes(label = Total), vjust = -0.5, size = 3) + labs(title = "Total Monthly Sales", x = "Month", y = "Total Sales") + ylim(0, 600) + theme_minimal() 图2:产品份额雷达图(使用条形图风格) product_totals <- sales_long %>% group_by(Product) %>% summarise(Total = sum(Sales)) plot2 <- ggplot(product_totals, aes(x = Product, y = Total, fill = Product)) + geom_bar(stat = "identity") + coord_polar(start = 0) + # 转换为极坐标,创建雷达效果 labs(title = "Product Sales Distribution") + theme_minimal() + theme(axis.text.y = element_blank(), axis.title = element_blank()) 图3:月度产品对比 plot3 <- ggplot(sales_long, aes(x = Month, y = Sales, fill = Product)) + geom_bar(stat = "identity", position = "dodge") + labs(title = "Monthly Product Comparison", x = "Month", y = "Sales") + scale_fill_brewer(palette = "Dark2") + theme_minimal() 组合图表 grid.arrange(plot1, plot2, plot3, ncol = 2, layout_matrix = rbind(c(1, 2), c(3, 3)))

7. 常见问题与解决方案

7.1 条形顺序控制

# 问题:条形按字母顺序排列,而非自定义顺序 # 解决方案:将因子水平按所需顺序设置 自定义月份顺序(财年顺序) custom_order <- c("Apr", "May", "Jun", "Jul", "Aug", "Sep") 创建示例数据 custom_data <- data.frame( Month = factor(c("Apr", "May", "Jun", "Jul", "Aug", "Sep"), levels = custom_order), # 设置因子水平 Sales = c(150, 180, 220, 190, 210, 240) ) ggplot(custom_data, aes(x = Month, y = Sales)) + geom_bar(stat = "identity", fill = "purple") + labs(title = "Bar Chart with Custom Order")

7.2 处理负值条形

# 包含负值的数据 profit_data <- data.frame( Quarter = c("Q1", "Q2", "Q3", "Q4"), Profit = c(120, -45, 80, -20) ) ggplot(profit_data, aes(x = Quarter, y = Profit, fill = Profit > 0)) + geom_bar(stat = "identity") + scale_fill_manual(values = c("TRUE" = "darkgreen", "FALSE" = "darkred"), name = "Profit Status", labels = c("Loss", "Gain")) + labs(title = "Quarterly Profit (with Negative Values)") + geom_hline(yintercept = 0, color = "black", size = 0.5) # 添加零线

7.3 大数据集优化

# 对于大量条形,使用水平条形图并排序 set.seed(456) big_data <- data.frame( Category = paste("Category", 1:20), Value = sample(100:500, 20) ) %>% arrange(Value) # 按值排序 ggplot(big_data, aes(x = reorder(Category, Value), y = Value)) + geom_bar(stat = "identity", fill = "steelblue") + coord_flip() + # 转换为水平条形图 labs(title = "Horizontal Bar Chart for Many Categories", x = "Category", y = "Value") + theme_minimal()

8. 总结与最佳实践

通过本文的学习,你应该已经掌握了在 R 中创建各种条形图的完整技能。以下是一些关键要点:

  • 选择正确的工具:快速探索使用基础barplot(),出版级图表使用 ggplot2。
  • 数据格式准备:ggplot2 通常需要长格式数据,使用melt()pivot_longer()转换。
  • 颜色与主题:使用 ColorBrewer 调色板或自定义颜色方案,保持图表美观且可读。
  • 标签与注释:添加清晰的标题、坐标轴标签、数值标签和图例。
  • 性能优化:大数据集考虑使用水平条形图、抽样或聚合展示。

条形图虽然基础,但通过巧妙的定制和组合,可以传达丰富的数据洞察。继续练习这些代码示例,并根据自己的数据特点进行调整,你将能够创建出既专业又美观的数据可视化作品。

9. 扩展学习资源

  • 官方文档?barplot?geom_bar
  • ggplot2 扩展包:ggthemes(更多主题)、ggpubr(出版级图表)
  • 交互式图表:plotly(将 ggplot2 转换为交互式图表)
  • 高级技巧:分面(facet)、动画(gganimate)、3D 条形图(lattice)