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

R语言如何基于3列数据框绘制总和为1的堆叠条形图

R 绘制对应数据的堆叠条形图

你无法直接用原始数据框画出堆叠条形图的核心原因是:你的数据是宽格式,ggplot2 等绘图包的堆叠条形图要求频率值存储在同一列,用单独的分类列区分不同分组,需要先做格式转换。
以下是可直接复现的代码:

  • 推荐用ggplot2实现(样式调整更灵活)
# 若未安装tidyverse请先运行:install.packages("tidyverse")
library(tidyverse)

# 导入你提供的原始数据
position <- c(1, 2, 3, 4, 5)
freq_1 <- c(0.1, 0.5, 0.4, 0.9, 1)
freq_2 <- 1 - freq_1
mydata <- data.frame(position, freq_1, freq_2)

# 宽格式转长格式,适配绘图要求
mydata_long <- mydata |> 
  pivot_longer(
    cols = starts_with("freq"),
    names_to = "group",
    values_to = "freq"
  )

# 绘图
ggplot(mydata_long, aes(x = factor(position), y = freq, fill = group)) +
  geom_col(width = 0.7) +
  # 自定义颜色和标签,可按需修改
  scale_fill_manual(
    values = c("#4E79A7", "#F28E2B"),
    labels = c("分组1", "分组2")
  ) +
  labs(x = "位置", y = "频率", fill = "分组") +
  scale_y_continuous(expand = c(0, 0), limits = c(0, 1.02)) +
  theme_bw() +
  theme(
    panel.grid.minor = element_blank(),
    legend.position = "top"
  )
  • 基础R原生函数实现(无需安装额外包)
barplot(
  height = rbind(mydata$freq_1, mydata$freq_2),
  names.arg = mydata$position,
  xlab = "位置",
  ylab = "频率",
  col = c("#4E79A7", "#F28E2B"),
  border = NA,
  space = 0.3
)
legend(
  "topleft",
  legend = c("分组1", "分组2"),
  fill = c("#4E79A7", "#F28E2B"),
  bty = "n",
  horiz = T
)

代码默认生成的堆叠柱总高度为1,和你需要的结构完全匹配,只需要修改颜色、标签、主题参数就能对齐你参考的示例样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:36:16