R语言使用分类变量绘制以state为x轴的条形图问题
R绘制指定条形图实现方案
1. 构造数据框
首先将你提供的原始数据构造为R可识别的结构化数据:
df <- data.frame( state = c("A", "B", "C", "D"), Avg_Earning = c(200, 350, 280, 520) )
2. 绘图实现
方案1:基础R内置函数实现(无需安装第三方包)
直接调用barplot()函数即可快速出图:
barplot( height = df$Avg_Earning, names.arg = df$state, # 指定x轴为state字段 xlab = "州", ylab = "平均收入", col = "steelblue", # 条形填充色可自定义 border = "white" )
方案2:ggplot2包实现(高可定制性)
如果需要更美观的可视化效果、后续调整空间更大,可以用ggplot2实现:
# 未安装包先执行:install.packages("ggplot2") library(ggplot2) ggplot(df, aes(x = state, y = Avg_Earning)) + geom_bar(stat = "identity", fill = "steelblue", color = "white") + labs(x = "州", y = "平均收入", title = "各州平均收入统计") + theme_bw()
注:geom_bar()中设置stat = "identity"是指定直接使用Avg_Earning的原始数值作为条形高度,无需做频次统计。
内容的提问来源于stack exchange,提问作者joy_1379
相关产品推荐
相关产品推荐

