Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I dynamically change the sign of ggplot labels but not the underlying data?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

enter image description here

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

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading