<p>一般金字塔密码</p>
<ol>
<li>避免在水平轴上设置标签打断</li>
<li>只使用一个<code>geom_*()</code>而不使用子设置数据,如果要在方面图中创建多个棱锥体,这尤其有用。</li>
<li>使用<code>geom_col()</code>而不是<code>geom_bar()</code>,后者具有更好的默认值<code>stat</code></li>
<li>具有相等的男性和女性水平轴;<code>limits = max(d$pop) * c(-1,1)</code>,以便在x轴上比较性别和相等标签。</li>
</ol>
<p>正在创建数据。。。</p>
<pre><code>set.seed(100)
a <- seq(from = 0, to = 90, by = 10)
d <- data.frame(age = paste(a, a + 10, sep = "-"),
sex = rep(x = c("Female", "Male"), each = 10),
pop = sample(x = 1:100, size = 20))
head(d)
# age sex pop
# 1 0-10 Female 74
# 2 10-20 Female 89
# 3 20-30 Female 78
# 4 30-40 Female 23
# 5 40-50 Female 86
# 6 50-60 Female 70
</code></pre>
<p>绘图代码。。。</p>
<pre><code>library(ggplot2)
ggplot(data = d,
mapping = aes(x = age, y = ifelse(test = sex == "Male", yes = -pop, no = pop),
fill = sex)) +
geom_col() +
coord_flip() +
scale_y_continuous(labels = abs, limits = max(d$pop) * c(-1,1)) +
labs(y = "Population")
</code></pre>
<p><a href="https://i.stack.imgur.com/0cdpv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0cdpv.png" alt="enter image description here"/></a></p>
<p>注意,如果你的数据是在个人层面上的,而不是按年龄性别组总结的,那么答案<a href="https://stackoverflow.com/a/37110346/513463">here</a>也很一般。</p>