Runic
Runic

Reputation: 149

How to change origin line position in ggplot bar graph?

Say I'm measuring 10 personality traits and I know the population baseline. I would like to create a chart for individual test-takers to show them their individual percentile ranking on each trait. Thus, the numbers go from 1 (percentile) to 99 (percentile). Given that a 50 is perfectly average, I'd like the graph to show bars going to the left or right from 50 as the origin line. In bar graphs in ggplot, it seems that the origin line defaults to 0. Is there a way to change the origin line to be at 50?

Here's some fake data and default graphing:

df <- data.frame(
  names = LETTERS[1:10],
  factor = round(rnorm(10, mean = 50, sd = 20), 1)
)

library(ggplot2)

ggplot(data = df, aes(x=names, y=factor)) +
  geom_bar(stat="identity") +
  coord_flip()

Upvotes: 3

Views: 2353

Answers (2)

uk_user
uk_user

Reputation: 13

This post was really helpful for me - thanks @ulfelder and @nongkrong. However, I wanted to re-use the code on different data without having to manually adjust the tick labels to fit the new data. To do this in a way that retained ggplot's tick placement, I defined a tiny function and called this function in the label argument:

fix.labels <- function(x){
  x + 50
}

ggplot(data = df, aes(x=names, y=factor - 50)) +
  geom_bar(stat="identity") +
  scale_y_continuous(labels = fix.labels) + ylab("Percentile") +
  coord_flip()

Upvotes: 1

ulfelder
ulfelder

Reputation: 5335

Picking up on @nongkrong's comment, here's some code that will do what I think you want while relabeling the ticks to match the original range and relabeling the axis to avoid showing the math:

library(ggplot2)
ggplot(data = df, aes(x=names, y=factor - 50)) +
  geom_bar(stat="identity") +
  scale_y_continuous(breaks=seq(-50,50,10), labels=seq(0,100,10)) + ylab("Percentile") +
  coord_flip()

Upvotes: 2

Related Questions