请求协助绘制X轴为年份、Y轴为百万单位的Density Plot
问题分析与解决方案
你的代码核心问题是未将年份设为密度图的X轴,也未处理Y轴的百万单位转换。以下是修正后的完整方案:
1. 确认数据集结构
假设你的数据集名为df,包含两列:
year:年份(需为数值型,如2000、2001...)welfare:对应的福利数值(后续会转换为百万单位)
2. 数据预处理(若需)
如果年份是字符型,先转为数值型:
df$year <- as.numeric(df$year)
3. 修正后的绘图代码
library(ggplot2) library(ggthemes) library(scales) # 用于格式化轴标签 ggplot(data = df, aes(x = year)) + # 绘制密度曲线,adjust可调整平滑程度 geom_density(fill = 'steelblue', color = 'black', adjust = 1.2) + # 设置X轴标签 scale_x_continuous(name = "年份") + # 将Y轴转换为百万单位显示 scale_y_continuous( name = "密度(百万单位)", labels = function(val) val / 1000000, breaks = seq(0, max(df$welfare, na.rm = TRUE)/1000000, by = 0.5) # 可根据数据调整间隔 ) + theme_economist()
补充方案(若需求为年份分组的福利密度)
如果你的实际需求是展示不同年份下福利数值的密度分布,而非年份本身的密度,可使用年份作为分组变量绘制多条曲线:
ggplot(data = df, aes(x = welfare/1000000, color = factor(year), fill = factor(year))) + geom_density(alpha = 0.3) + scale_x_continuous(name = "福利(百万单位)") + scale_y_continuous(name = "密度") + theme_economist() + labs(color = "年份", fill = "年份")
内容的提问来源于stack exchange,提问作者Artesanal_Panettone
相关产品推荐
相关产品推荐

