Home > Net >  How to fix y-axis label overlapping on ggplot in R?
How to fix y-axis label overlapping on ggplot in R?

Time:04-14

My y-axis for Age groups keep overlapping. Please help! This is my code:

ggplot(data = BRFSS2015_outlier1, aes(x = INCOME2, y= Age, color = SEX)) 
  geom_col(width=0.03) 
  facet_grid(.~SEX) 
  labs(x = "Age") 
  theme(axis.text.x = element_text(angle = 30))

The output looks like this: enter image description here

CodePudding user response:

It will help to see a sample of data using dput(BRFSS2015_outlier1) or if that's too long dput(head(BRFSS2015_outlier1)).

My guess is that Age is stored as a factor, and you haven't summarized, so each column is stacking many observations, resulting in tall columns that are way out of scale with the limited number of Age factors that are displayed in the y axis. You might, for instance, have an Age "30" which might be the first factor, appearing at "1" on the y axis, and Age "40" as the 2nd factor appearing at "2" on the y axis, but those are basically 0 compared to your stack that is hundreds or thousands of observations high.

Here's a reproducible example using data we all have already. Note that the y axis labels are all overlapped on the bottom like in your example.

ggplot(data = diamonds, aes(x = cut, y= as.factor(cut), color = clarity)) 
  geom_col(width=0.03) 
  facet_grid(.~color) 
  theme(axis.text.x = element_text(angle = 30))

enter image description here

It's unclear to me what you want to show with Age on the y axis. Is each bar supposed to be "as tall" as the Age? Or do you want to show how many observations there are of each age?

I'm guessing you wanted to show how the income distribution varies with Age, in which case it might be more appropriate to use Age as the vertical faceting variable, like this (replace "cut" here with Age in your example). Note also the use of geom_bar (which by default counts and displays the number of observations) instead of geom_col (which by default shows the raw value).

ggplot(data = diamonds, aes(x = cut, fill = cut)) 
  geom_bar() 
  facet_grid(color~clarity) 
  theme(axis.text.x = element_text(angle = 30))

enter image description here

  • Related