如何使RStudio绘制的金字塔图左侧显示正值?附相关代码
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
Make text labels display positive values
Modify thelabelargument ingeom_textto useabs(prop)instead of justprop. This way, even though the underlying value stays negative for correct positioning, the displayed label will be positive.Fix the invalid ggplot syntax
Your original code incorrectly tried to nestgeom_bar()inside theaes()call ofggplot()—that's not valid R syntax. You need to chain geoms using+after the initialggplot()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

