如何将ggplot2条形图的负x轴断点(标签)更改为正值?

时间:2016-08-08 11:38:02

标签: r ggplot2

我的数据框看起来像这样:

df <- structure(list(gender = c("male", "male", "male", "female", "female", 
"female", "male", "male", "male", "male", "male", "female", "female", 
"female"), agegroup = c("-24", "25-34", "45-54", "-24", "25-34", 
"35-44", "-24", "25-34", "35-44", "65-", "unknown", "-24", "25-34", 
"35-44"), N = c(-2, -4, -1, 3, 4, 1, -3, -14, -1, -1, -2, 3, 
3, 1), N2 = c(2, 4, 1, 3, 4, 1, 3, 14, 1, 1, 2, 3, 3, 1), location = c("here", 
"here", "here", "here", "here", "here", "there", "there", "there", 
"there", "there", "there", "there", "there")), .Names = c("gender", 
"agegroup", "N", "N2", "location"), row.names = c(NA, 14L), class = "data.frame")

我需要将N的一部分变为否定因为我想制作一个金字塔&#34;。像这样:

ggplot(biofile2, aes(x = agegroup, y = N , fill = gender),color=gender) +
geom_bar(stat="identity", size=.3, position="identity")+
facet_wrap(~ location,ncol=2)+ 
coord_flip()

看起来像我的意图。剩下的就是将-10和-5改回正数。有没有办法在不改变情节外观的情况下做到这一点?

1 个答案:

答案 0 :(得分:1)

似乎您想简单地使所有轴标签为正,即取绝对值。我们可以使用带有scale_*_continuousbreaks参数的labels来执行此操作。请注意,在这种情况下,我们需要变换y轴,因为我们必须在 coord_flip之前引用轴pretty函数可用于方便地生成一些漂亮的轴断点:

添加你的情节:

scale_y_continuous(breaks = pretty(df$N), labels = abs(pretty(df$N))