I am creating a population pyramid in ggplot and in order to get the bars to show correctly, I have changed the sign of one category to negative by multiplying the variable by -1.
The problem is now that I have the bars looking correctly but the axis labels show negative numbers. I am wondering how I change the sign dynamically (i.e. I cannot manually specify specific labels because the charts are being created in a loop and some will have different ranges). The code for the plot and an image are below.
Thank you
PyramidPlot <- ggplot() +
geom_bar(data = PopEDMalesFullLessT, aes(x = Age, y = Percentage, fill = "red"), width= 0.4,
position = position_nudge(0.22), stat = "identity") +
geom_bar(data = PopEDFemalesFullLessT, aes(x = Age, y = Percentage, fill = "blue"), width= 0.4,
position = position_nudge(0.22), stat = "identity") +
scale_x_discrete(name = "Age Group")+
labs(fill = "Legend") +
theme_classic()+
theme(axis.text.x = element_text(margin = margin(t = 0.25, unit = "in")),
axis.title.x = element_text(margin = margin(0.1, 0, 0.1, 0)),
legend.position = c(0.9, 0.9)
)+
coord_flip()+
scale_fill_discrete(labels=c('Males', 'Females'))
>Solution :
You can give functions to the labels argument of a ggplot scale, in which case the function will be applied to the default labels. In this case, the absolute value function abs will work. See ?continuous_scale for details and other options.
data.frame(x = 1:3, y = (-1):1) |>
ggplot(aes(x, y)) + geom_point() +
scale_y_continuous(labels = abs)

