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

如何在R中生成刻度起点为0.7而非0的金字塔图

调整金字塔图刻度起点至0.7的解决方案

你可以通过自定义scale_y_continuous的刻度范围和断点来实现需求,修改后的完整代码如下:

library(tidyverse)
library(ggpol)

df <- tibble(
  Population = c(5, 8.7, 16.7, 24.8, 38, -4.6, -6.4, -16.1, -39.6, -55.3),
  Gender = c("Male", "Male", "Male", "Male", "Male", "Female", "Female", 
             "Female", "Female", "Female"),
  AgeBand = c("65-69", "70-74", "75-79", "80-84", "85+", "65-69", "70-74", 
              "75-79", "80-84", "85+")
)

ggplot(df, aes(x = AgeBand, y = Population, fill = Gender)) +
  geom_bar(stat = "identity") +
  facet_share(~Gender, dir = "h", scales = "free", reverse_num = TRUE) +  
  coord_flip() +
  theme_minimal() +
  labs(y = "Count", x = "Age Band", title = " ") +
  scale_fill_manual(values = c("pink", "blue")) +
  # 自定义y轴刻度,设置起点为0.7/-0.7
  scale_y_continuous(
    limits = function(x) {
      # 针对男性(正值)和女性(负值)分面分别设置刻度范围
      if (max(x) > 0) {
        c(0.7, max(x))
      } else {
        c(min(x), -0.7)
      }
    },
    breaks = function(x) {
      # 生成对应范围的刻度断点,保持间隔为10
      if (max(x) > 0) {
        seq(0.7, max(x), by = 10)
      } else {
        seq(min(x), -0.7, by = 10)
      }
    }
  )

修改说明:

  • 通过scale_y_continuous的limits参数,针对男性(正值)分面设置y轴下限为0.7,女性(负值)分面设置y轴上限为-0.7,实现刻度从0.7/-0.7开始的效果。
  • breaks参数用于生成对应范围的刻度断点,保持原有的10单位间隔,让刻度显示更规整。
  • 因为facet_share设置了scales="free",所以每个分面会独立应用自定义的刻度规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:37:02