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

geom_function绘制选票第二位数分布时偏移问题求助

问题解决:第二位数预期分布线偏移的修复

问题根源

你的x轴是因子类型:第二位数的digit是0-9的因子,ggplot在绘制因子轴时,会把每个因子级别映射到底层连续数值1到10(0对应1,1对应2,…,9对应10)。但geom_function使用的是你指定的xlim=c(0,9)连续区间,两者的坐标映射不匹配,导致函数线整体左移一个单位。

而第一位数的digit是1-9,转成因子后底层数值正好是1-9,和geom_function的xlim=c(1,9)完全对应,所以没有偏移问题。

两种修复方案

方案一:将x轴转为连续型(推荐)

直接把graph_data中的digit从因子转为数值型,让ggplot使用连续x轴,和geom_function的坐标完全对齐:

修改graph_data的生成代码:

graph_data <- data %>%
  group_by(digit, state, party_simplified) %>%
  mutate(digit = as.numeric(digit)) %>%  # 替换原as.factor为as.numeric
  summarise(n = n()) %>%
  ungroup() %>%
  group_by(state, party_simplified) %>%
  mutate(prop = n/sum(n))

然后在ggplot中添加x轴刻度设置,确保显示0-9的标签:

plot <- ggplot(graph_data, aes(x = digit, y = prop, group = party_simplified, 
                               color = party_simplified)) +
  geom_line(stat = "identity") +
  geom_function(fun = ~expected(.x), color = "grey", xlim = c(0, 9)) +
  geom_point() +
  facet_wrap(vars(state))+
  scale_y_continuous(labels = scales::percent_format(scale=100)) +
  scale_x_continuous(breaks = 0:9, labels = 0:9) +  # 新增x轴刻度设置
  labs(title = sprintf("Distribution of the %s Digit by Party", digit),
       color = "Party", y = "Percentage", x = "Digit") +
  scale_color_manual(values=c("blue", "red"))

方案二:调整geom_function的输入映射

如果要保留因子x轴,只需调整geom_function的输入参数,匹配因子的底层坐标:

把原代码中的geom_function行替换为:

geom_function(fun = ~expected(.x - 1), color = "grey", xlim = c(1, 10))

解释:因子0对应x=1,给expected函数传入.x-1后,x=1时输入0,x=10时输入9,正好覆盖第二位数的0-9区间,线条就会和实际数据对齐。

验证

两种方案都能让灰色预期线和红蓝数据线条从x=0开始对齐,且函数输出值保持正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:35:08