You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用独特样式将条形图的条形补全至100%?

在百分比条形图中补全条形至100%(带虚线)

你可以通过ggplot2的geom_segment()函数绘制垂直虚线,将每个条形补全至100%的位置,具体实现代码如下:

library(ggplot2)
library(tibble)

my_df <- tribble(~step, ~prop,
                   "a", 1,
                   "b", 0.8,
                   "c", 0.55,
                   "d", 0.2
)

my_df |> 
  ggplot(aes(x = step, y = prop)) +
  geom_col(fill = "#619CFF") +
  # 绘制补全至100%的虚线
  geom_segment(
    aes(x = step, xend = step, y = prop, yend = 1),
    linetype = "dashed", 
    color = "gray50"
  ) +
  # 可选:将Y轴转换为百分比格式
  scale_y_continuous(labels = scales::percent) +
  labs(x = "步骤", y = "百分比")

关键说明:

  • geom_segment() 是核心:通过指定x和xend为step,保证虚线与对应条形对齐;y取现有条形的高度prop,yend设为1(对应100%),从而画出垂直补全线段
  • 可通过linetype和color参数自定义虚线的样式和颜色,适配不同视觉需求
  • 添加scale_y_continuous(labels = scales::percent)可以让Y轴显示百分比文本,更贴合图表主题

内容的提问来源于stack exchange,提问作者Emman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 05:10:11