0

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.

Joehat
  • 979
  • 1
  • 9
  • 36
  • Does it work without the `scale_x_continuous()`? I think the breaks/labels might contain duplicates or too many values. – teunbrand Mar 17 '21 at 10:58
  • Yes, it does. But I'd like to see all the hour values so 00, 01, 02, 03... Any suggestions? – Joehat Mar 17 '21 at 11:00

1 Answers1

1

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 !
abreums
  • 166
  • 8
  • I changed it to scale_x_continuous(labels = 0:23, breaks = 0:23) so it starts at midnight. However, doing it this way, the x-axis would have 0, 1, 2, ... Is there a way of keeping it with 2 digits to better resemble hours? i.e., 00, 01, 02, ... – Joehat Mar 17 '21 at 11:06
  • 1
    Try `labels = formatC(0:23, width = 2, flag = "0")`. – teunbrand Mar 17 '21 at 11:56
  • yeap! Correcting as suggested by @teunbrand! – abreums Apr 26 '21 at 11:33