在R中为2022-2023年月度价格柱状图添加变化百分比标注
解决方案
先修正原代码的变量名不一致问题,补充数据预处理逻辑(原代码未处理日期、价格格式,会导致后续计算报错),再添加百分比计算与标注功能:
步骤1:数据预处理与月度总价计算
先转换日期格式、清洗价格列(去除欧元符号与逗号,转为数值型),再按年、月分组计算总价:
# 加载依赖包 library(plotly) library(tidyr) library(dplyr) # 构造数据集 df <- data.frame( Date = c("30/10/2022", "31/10/2022", "01/11/2022", "02/11/2022", "01/12/2022", "02/12/2022", "01/10/2023", "02/10/2023", "08/11/2023", "09/12/2023", "10/12/2023"), Price = c("129,60 €", "106,10 €", "87,40 €", "103,80 €", "60,00 €", "380,50 €", "243,40 €", "76,00 €", "318,30 €", "156,30 €", "49,00 €") ) # 数据清洗 df$Date <- as.Date(df$Date, format = "%d/%m/%Y") df$Price <- as.numeric(gsub("[,€ ]", "", df$Price)) # 去除无关符号,转数值型 # 提取年月并计算月度总价 df$Month <- format(df$Date, "%m") df$Year <- format(df$Date, "%Y") total_month <- aggregate(Price ~ Month + Year, df, sum)
步骤2:计算月度价格变化百分比
将长格式数据转为宽格式,方便计算2023年相对2022年的变化率:
# 转宽格式:每行对应一个月份,列存储对应年份的总价 wide_total <- pivot_wider(total_month, names_from = Year, values_from = Price, values_fill = 0) # 计算变化百分比,保留1位小数,避免除以0错误 wide_total$pct_change <- ifelse(wide_total$`2022` != 0, round((wide_total$`2023` - wide_total$`2022`)/wide_total$`2022`*100, 1), NA)
步骤3:绘制带百分比标注的分组柱状图
用plot_ly绘制分组柱形图,通过add_annotations添加变化百分比标注,放在对应月份双柱的中间上方:
# 绘制分组柱状图 plot <- plot_ly(total_month, x = ~Month, y = ~Price, color = ~Year, type = "bar") %>% layout( barmode = "group", xaxis = list(title = "月份"), yaxis = list(title = "总价"), legend = list(title = "年份") ) %>% # 添加百分比标注 add_annotations( x = wide_total$Month, y = pmax(wide_total$`2022`, wide_total$`2023`) + 20, # 标注位置在当月最高柱子上方20单位 text = paste0(wide_total$pct_change, "%"), showarrow = FALSE, font = list(size = 10) ) # 显示图表 plot
关键说明
- 数据清洗是核心前提:原数据的价格为带符号的字符串,必须转为数值型才能计算;日期需转标准格式才能正确提取年月。
- 变化百分比计算加入了非零判断,避免2022年无数据时出现除以0的报错。
- 标注位置取对应月份两年总价的最大值,确保标注不会被柱子遮挡。
内容的提问来源于stack exchange,提问作者cik renna
相关产品推荐
相关产品推荐

