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

基于边际频率表在ggplot2分面中绘制边缘密度/条形图的咨询

在ggplot2中绘制分面边际频率图的实现方法

没问题!要在ggplot2里用分面展示你提供的边际频率数据,核心是先把宽格式数据转成ggplot偏好的长格式,再通过分面函数实现子组(a到h)的单独图表。下面是完整的步骤和代码:

1. 准备原始数据

首先把你的表格数据转换成R的data.frame:

# 构造宽格式的边际频率数据
df_wide <- data.frame(
  group = c("a", "b", "c", "d", "e", "f", "g", "h"),
  `0` = c(0.019, 0.058, 0.026, 0.054, 0.004, 0.032, 0.113, 0.328),
  `1-5` = c(0.300, 0.448, 0.277, 0.297, 0.252, 0.097, 0.500, 0.460),
  `6-10` = c(0.296, 0.308, 0.316, 0.378, 0.358, 0.312, 0.233, 0.129),
  `11-15` = c(0.211, 0.120, 0.187, 0.108, 0.216, 0.280, 0.094, 0.050),
  `16-20` = c(0.117, 0.042, 0.105, 0.108, 0.102, 0.161, 0.043, 0.020),
  `21-26` = c(0.042, 0.019, 0.068, 0.041, 0.053, 0.065, 0.014, 0.010),
  `27-29` = c(0.014, 0.005, 0.020, 0.014, 0.015, 0.054, 0.003, 0.003)
)

2. 转换为长格式数据

ggplot2需要每一行对应一个观测值,所以用tidyr的pivot_longer函数转换格式:

# 加载tidyverse包(包含ggplot2和tidyr)
library(tidyverse)

# 宽格式转长格式
df_long <- df_wide %>%
  pivot_longer(
    cols = -group,          # 排除group列,转换其他所有列
    names_to = "range",     # 新列:存储区间名称
    values_to = "frequency" # 新列:存储边际频率值
  )

3. 绘制分面条形图(推荐)

因为你的数据是离散区间的边际频率,条形图是最直观的展示方式:

ggplot(df_long, aes(x = range, y = frequency, fill = range)) +
  geom_bar(stat = "identity", width = 0.8) +  # 直接使用已有频率值,无需统计
  facet_wrap(~group, ncol = 2) +              # 按group分面,每行4个图(2列)
  labs(
    title = "各子组边际频率分布",
    x = "数值区间",
    y = "边际频率"
  ) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1), # 旋转x轴标签避免重叠
    legend.position = "none"                           # 区间一致,无需图例
  )

4. 绘制分面密度趋势图(可选)

如果想展示频率随区间的变化趋势,可以给每个区间设置中点值,再用线条模拟密度趋势:

# 为每个区间添加中点数值
df_long <- df_long %>%
  mutate(
    midpoint = case_when(
      range == "0" ~ 0,
      range == "1-5" ~ 3,
      range == "6-10" ~ 8,
      range == "11-15" ~ 13,
      range == "16-20" ~ 18,
      range == "21-26" ~ 23.5,
      range == "27-29" ~ 28
    )
  )

# 绘制分面密度趋势图
ggplot(df_long, aes(x = midpoint, y = frequency)) +
  geom_line(aes(group = 1), color = "#2c3e50", linewidth = 1) +
  geom_point(color = "#e74c3c", size = 2) +
  facet_wrap(~group, ncol = 2) +
  labs(
    title = "各子组边际频率趋势",
    x = "区间中点值",
    y = "边际频率"
  ) +
  theme_minimal()

小提示

  • 可以用facet_grid(~group)替代facet_wrap,固定分面的行列布局
  • 如果需要调整分面的间距或标题样式,可以修改theme里的panel.spacing、strip.text等参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:35:42