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

如何使RStudio绘制的金字塔图左侧显示正值?附相关代码

Fixing Negative Values on the Left Side of Your Pyramid Plot in R

Let's break down how to fix those negative values showing up on the left side of your pyramid plot, plus tidy up a small syntax glitch in your code.

What's Causing the Negative Labels?

Looking at your code, you're calculating the prop column with negative values for males (-N/sum(N))—this makes sense for positioning them on the left when using coord_flip(). However, your geom_text is using the raw negative prop values to display labels, so those end up showing as negatives even though your y-axis uses abs() to render positive tick marks.

Step-by-Step Fixes

  1. Make text labels display positive values
    Modify the label argument in geom_text to use abs(prop) instead of just prop. This way, even though the underlying value stays negative for correct positioning, the displayed label will be positive.

  2. Fix the invalid ggplot syntax
    Your original code incorrectly tried to nest geom_bar() inside the aes() call of ggplot()—that's not valid R syntax. You need to chain geoms using + after the initial ggplot() setup.

Updated Code Snippet

Here's the corrected section of your code with these changes applied:

piramides <- lapply(split(idades_prop, by = "vila"), function(data){
  vila_n <- data[,unique(vila)]
  ggplot(data, aes(x = idade_5, y = prop, fill = sexo_label)) + # Map fill here for consistent grouping
    geom_bar(stat = "identity") + # Single geom_bar handles both genders with fill mapping
    geom_text(aes(label = format(abs(prop), digits=2)), # Use abs() to show positive labels
              hjust = "outward", size = 2, 
              position = position_dodge(width = 1), 
              check_overlap = TRUE) + 
    scale_y_continuous(labels = abs, limits = max_prop*c(-1,1), breaks = seq(-max_prop, max_prop, by = 5)) + 
    scale_x_continuous(expand=c(0,0), breaks = seq(0,120, by = 5)) + 
    coord_flip() + 
    labs(title = vila_n, y = "% de pessoas", x = "Idade (5 em 5 anos)", fill = "Gênero")
})

Quick Extra Tip

I removed the separate geom_bar() calls for each gender—mapping fill = sexo_label in the main aes() and using one geom_bar(stat="identity") makes the code cleaner and ensures your legend works as expected. The hjust = "outward" will keep labels properly aligned away from bars (left for males, right for females) even with positive values.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:53:59