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

如何在ggplot的facet_grid中设置X轴为对应分组的分数形式?

解决方案

要实现分面后X轴比例按对应分组n显示为分数,核心是给每个分面单独设置X轴标签。这里推荐使用ggh4x包的facetted_pos_scales功能,它支持为不同分面定制坐标轴:

步骤1:准备环境与数据

# 安装并加载依赖包
if (!require(ggh4x)) install.packages("ggh4x")
library(ggh4x)
library(tidyverse)

# 原始数据
index = c(1:10)
n = c(3,1,2,2,2,4,2,4,4,4)
prop = c(0,0,0,0.5,0.5,0.25,0.5,0,0,0.25)
df <- data.frame(index,n,prop)

步骤2:定义分面专属X轴刻度

针对每个唯一的n值,生成对应的刻度断点和分数标签:

n_unique <- unique(df$n)
x_scale_list <- setNames(lapply(n_unique, function(current_n) {
  # 保持原有的刻度断点
  breaks <- seq(0, 1, 0.5)
  # 生成对应分数标签:0直接显示为"0",其他按(prop*n)/n格式
  labels <- case_when(
    breaks == 0 ~ "0",
    TRUE ~ paste0(breaks * current_n, "/", current_n)
  )
  scale_x_continuous(breaks = breaks, labels = labels)
}), as.character(n_unique))

步骤3:绘制图形

在原有绘图代码基础上,添加facetted_pos_scales应用定制的X轴:

df %>%
  ggplot(aes(x = prop)) +
  geom_bar(fill = "#D294B2", width = 0.2) +
  facet_grid(~n) +
  labs(title = "Porportion of x in index with 2 or more", 
       x = "Proportion of x", 
       y = "No. of index") +
  geom_text(stat='count', aes(label=..count..), hjust=0.5, vjust=-0.5, size=3) +
  scale_y_continuous(limits = c(0,10)) +
  # 为每个分面应用专属X轴
  facetted_pos_scales(x = x_scale_list) +
  theme_bw()

额外说明

  • 如果希望分数自动化简(比如n=4时0.5显示为1/2而非2/4),可以把标签生成逻辑替换为:
    labels <- case_when(
      breaks == 0 ~ "0",
      TRUE ~ as.character(fractions(breaks))
    )
    
  • 不要将X轴转为离散型(scale_x_discrete),因为prop是连续变量,转离散会破坏柱状图的位置对应关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 18:46:09