rdatasculptor
rdatasculptor

Reputation: 8447

How to change negative x axis breaks (labels) of ggplot2 bar graph into positive ones?

I have a dataframe that looks like this one:

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")

I needed to make some of the N's into negatives because I wanted to make a "pyramid". Like this:

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()

It looks like I intended. All that is left is to change the -10 and -5 back into positives. Is there a way to do that without changing the appearance of the plot?

Upvotes: 2

Views: 2851

Answers (1)

Axeman
Axeman

Reputation: 35382

It seems like you want to simply make all axis labels positive, i.e. take the absolute value. We can do this using scale_*_continuous with the breaks and labels arguments. Note that in this case we need to transform the y-axis, since we have to refer to the axis before coord_flip. The pretty function can be used to conveniently generate some pretty axis breaks:

Add this your plot:

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

Upvotes: 3

Related Questions