Search code examples
rggplot2axis-labelsgeom-col

R: Continuous scale on the x-axis using ggplot


I am trying to plot hourly values on the x-axis (from 00 to 23).

However, when trying the code below, it ends up crashing my R Studio. I'm wondering if there's a step I am missing or if I am using the wrong code to achieve this.

> glimpse(df_temp$Start.Hour)
 int [1:496728] 18 17 9 8 20 20 0 21 13 16 ...
# Trip distance by time of the day
p5 <- ggplot(df_temp, aes(x=Start.Hour, y=Trip.Distance)) +
  geom_col(fill="salmon") +
  labs(title="Trip Distance by Time of the Day",
      x="Hour of the Day",
      y="Distance (km)") +
      theme_bw() +
  theme(plot.title=element_text(size=14, face="bold")) +
  theme(axis.title.x=element_text(size = 12, face = "bold")) +
  theme(axis.text.x=element_text(size=10, face = "bold")) + 
  theme(axis.title.y=element_text(size=12, face = "bold")) +
  theme(axis.text.y=element_text(size=10, face = "bold")) +
  scale_x_continuous(labels = as.character(df_temp$Start.Hour), breaks = df_temp$Start.Hour)
  
p5

This is what I get without the scale_x_continuous()

enter image description here

And this is what I'd like to achieve: enter image description here

NOTE: Different datasets are used in both plots.


Solution

  • In the scale_x_continuous function, labels and breaks should not refer to the whole vector of values. Instead, you should try: labels = 0:23 and breaks = 0:23

    p5 <- ggplot(df_temp, aes(x=Start.Hour, y=Trip.Distance)) +
      geom_col(fill="salmon") +
      labs(title="Trip Distance by Time of the Day",
           x="Hour of the Day",
           y="Distance (km)") +
      theme_bw() +
      theme(plot.title=element_text(size=14, face="bold")) +
      theme(axis.title.x=element_text(size = 12, face = "bold")) +
      theme(axis.text.x=element_text(size=10, face = "bold")) + 
      theme(axis.title.y=element_text(size=12, face = "bold")) +
      theme(axis.text.y=element_text(size=10, face = "bold")) +
      scale_x_continuous(labels = 0:23, breaks = 0:23)       # changes only here !