改变人口金字塔中的 y 轴数字

时间:2021-06-23 20:18:59

标签: r

我再次发布了这个问题并给出了一个答案,但是当我再次发布时,我没有给出相同的输出。 我有一个名为 mydata 的数据框,其中包含不同 country 的人口。

df<- data_frame(age= c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70), gender = "male", 
population =c(180,160,130,140,150,160,170,90,85,80,75,70,65,60,40), country = 1)
                
df1<- data_frame(age= c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70), gender = "female", 
population =c(160,150,120,130,140,150,160,80,75,70,65,60,55,50,30),country  = 1)

df2<- data_frame(age= c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70), gender = "male", 
population =c(80,77,66,65,69,69,54,50,44,40,38,29,20,12,8), country = 2)

df3<- data_frame(age= c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70), gender = "female",
population =c(76,70,61,63,60,51,41,39,37,33,30,28,23,22,10), country = 2)

df4<- data_frame(age= c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70), gender = "male", 
 population =c(29,27,30,26,24,22,20,18,16,14,12,10,8,6,4), country = 3)

df5<- data_frame(age= c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70), gender = "female",
population =c(28,24,20,22,23,24,22,21,20,18,16,13,12,10,6), country = 3)


mydata<- rbind(df,df1,df2,df3,df4,df5)

在下面的代码中,我得到了三个国家的人口金字塔。由于每个国家的人口数量不同,我的人口金字塔在视觉上不同且不可比,我如何更改 y 轴以便我有一个可比的人口金字塔?

ggplot(data=mydata, aes(x=age, y = ifelse(gender == "male", -population, population), fill=gender)) + 
  geom_col() + 
  facet_wrap(~country) +
  coord_flip()

enter image description here

1 个答案:

答案 0 :(得分:1)

正如@Stefan 建议的那样,将 scales = "free_x" 添加到 facet_wrap 允许每个 x 轴自由缩放(取决于数据)。

library(ggplot2)
ggplot(data=mydata, aes(x=age, y = ifelse(gender == "male", -population, population), fill=gender)) + 
  geom_col() + 
  facet_wrap(~country, scales = "free_x") +
  coord_flip()

enter image description here

相关问题