技术问询:使用ggplot2绘制仿Excel Kutools风格的双变量对比柱状图
用R绘制类似Excel Kutools的对比柱状图
首先准备示例数据:
df <- data.frame(Unit = c("unit1", "unit2", "unit3"), Aktual = c(1500, 2200, 3000), Target = c(1600, 2100, 2900))
要实现和Kutools类似的对比效果,我们需要先把宽格式数据转换为ggplot2适配的长格式,再绘制并列柱状图,还可以添加数值标签和差值标注还原Kutools的细节:
步骤1:加载依赖包并转换数据格式
library(tidyverse) # 将宽格式转为长格式,方便分组绘图 df_long <- df %>% pivot_longer(cols = -Unit, names_to = "Type", values_to = "Value")
步骤2:基础对比柱状图(还原Kutools核心布局)
ggplot(df_long, aes(x = Unit, y = Value, fill = Type)) + # 设置并列柱子,调整间距让布局更紧凑 geom_col(position = position_dodge(width = 0.8), width = 0.7) + # 使用类似Excel的配色区分实际值和目标值 scale_fill_manual(values = c("Aktual" = "#1f77b4", "Target" = "#ff7f0e")) + # 设置图表标题和坐标轴标签 labs(title = "实际值vs目标值对比", x = "单位", y = "数值", fill = "类型") + # 采用简洁的主题风格 theme_minimal() + # 调整标题和图例位置 theme(plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.title = element_text(size = 12), legend.position = "top")
步骤3:增强版(添加数值标签和差值标注)
如果需要和Kutools一样显示柱子数值以及实际与目标的差值,可以额外计算差值并添加标注:
# 计算每个单位的差值并生成标注文本 df_diff <- df %>% mutate(Diff = Aktual - Target, Diff_Label = ifelse(Diff >= 0, paste("+", Diff), as.character(Diff))) ggplot(df_long, aes(x = Unit, y = Value, fill = Type)) + geom_col(position = position_dodge(width = 0.8), width = 0.7) + # 在柱子顶部添加数值标签 geom_text(aes(label = Value), position = position_dodge(width = 0.8), vjust = -0.5, size = 4) + # 在每个单位上方添加差值标注 geom_text(data = df_diff, aes(x = Unit, y = max(Value) * 1.1, label = Diff_Label), size = 4, color = "red", fontface = "bold") + scale_fill_manual(values = c("Aktual" = "#1f77b4", "Target" = "#ff7f0e")) + labs(title = "实际值vs目标值对比", x = "单位", y = "数值", fill = "类型") + # 调整y轴范围,留出标注空间 ylim(0, max(df$Value) * 1.2) + theme_minimal() + theme(plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.title = element_text(size = 12), legend.position = "top")
这个实现完全匹配Kutools对比柱状图的效果:每个类别下并列显示两组数据,配色清晰,附带关键数值和差异标注,布局整洁直观。
内容的提问来源于stack exchange,提问作者Fadhil Dzikri
相关产品推荐
相关产品推荐

