-1

I am trying to change the way the x labels on the x axis are represented in ggplot2 histogram, so that instead of being 0, 10, 20, 30, its shown 0-10, 10-20, 20-30, 30-40 etc.

I know this can be done manually but I was wondering if there was a more simple method.

newbie
  • 21
  • 5

1 Answers1

0

Assuming you have data like this :

set.seed(123)
vec <- sample(1:50, 100, replace = TRUE)
df <- data.frame(vec)

And you already have the group column, you can create labels column.

library(dplyr)
library(ggplot2)

df %>% 
  mutate(group = ceiling(vec/10) * 10, 
         labels = paste(group-10, group, sep = '-')) -> df1

and use scale_x_continuous in geom_histogram :

ggplot(df1) + aes(group) + 
  geom_histogram(bins = 5) +
  scale_x_continuous(breaks = unique(df1$group), labels = unique(df1$labels))

enter image description here

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you, however is there a way of doing this directly in ggplot2 rather than mutating? – newbie Jan 05 '21 at 09:21
  • @newbie Sure it is possible but for it you should provide your data in a reproducible format that we can copy-paste. You have provided no information in your question about how your data looks like. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Jan 06 '21 at 03:32