R语言ggplot绘制三列数据报错,求正确实现方法
解决ggplot宽数据可视化的错误问题
错误原因
你的数据集是宽格式(单一行包含3个类别的事故数值),而ggplot要求输入长格式数据(每行对应一个类别-数值对),直接在aes中用1:3和c(pedestrians, motorist, cyclist)会导致美学映射长度与数据行数(1行)不匹配,触发错误。
解决方法:转换数据为长格式再绘图
方法1:使用tidyr包快速转换(推荐)
# 安装并加载依赖包(首次运行需安装) # install.packages(c("ggplot2", "tidyr")) library(ggplot2) library(tidyr) # 将宽格式数据转为长格式 df_long <- pivot_longer(df3, cols = everything(), # 选择所有列 names_to = "mode", # 类别列的名称 values_to = "accidents") # 数值列的名称 # 绘制柱状图 ggplot(df_long, aes(x = mode, y = accidents)) + geom_col() + ggtitle("Accidents by Mode of Transportation") + scale_x_discrete(labels = c("Pedestrians", "Motorists", "Cyclists"))
方法2:手动构造长格式数据
如果不想额外加载tidyr包,也可以手动创建长格式数据集:
library(ggplot2) # 手动构造长格式数据 df_long <- data.frame( mode = c("pedestrians", "motorist", "cyclist"), accidents = c(df3$pedestrians, df3$motorist, df3$cyclist) ) # 绘图 ggplot(df_long, aes(x = mode, y = accidents)) + geom_col() + ggtitle("Accidents by Mode of Transportation") + scale_x_discrete(labels = c("Pedestrians", "Motorists", "Cyclists"))
效果说明
转换后的数据是3行结构,每行对应一种交通模式和对应的事故数量,此时ggplot的美学映射长度与数据行数一致,能够正常绘制出3个柱状条的图表。
内容的提问来源于stack exchange,提问作者diorzyon
相关产品推荐
相关产品推荐

