R:使用 ggplot 在 x 轴上连续刻度

R: Continuous scale on the x-axis using ggplot

我正在尝试在 x 轴(从 00 到 23)上绘制每小时值。

但是,在尝试下面的代码时,它最终导致我的 R Studio 崩溃。我想知道我是否遗漏了某个步骤,或者我是否使用了错误的代码来实现此目的。

> 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

这是我没有 scale_x_continuous()

得到的结果

这就是我想要实现的目标:

注意:两个图中使用了不同的数据集。

在 scale_x_continuous 函数中,标签和分隔符不应引用整个值向量。 相反,您应该尝试: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 !