【问题标题】:R: Continuous scale on the x-axis using ggplotR:使用ggplot在x轴上连续缩放
【发布时间】:2021-06-14 16:34:11
【问题描述】:

我正在尝试在 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() 是否可以工作?我认为中断/标签可能包含重复或太多值。
  • 是的,确实如此。但我想查看所有小时值,所以 00、01、02、03... 有什么建议吗?

标签: r ggplot2 axis-labels geom-col


【解决方案1】:

在 scale_x_continuous 函数中,标签和中断不应引用整个值向量。 相反,您应该尝试:标签 = 0:23 和休息 = 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 !

【讨论】:

  • 我把它改成了 scale_x_continuous(labels = 0:23, breaks = 0:23) 所以它从午夜开始。但是,这样做,x 轴将有 0、1、2,...... 有没有办法让它保持 2 位数字以更好地模拟小时?即,00, 01, 02, ...
  • 试试labels = formatC(0:23, width = 2, flag = "0")
  • 是的!按照@teunbrand 的建议进行更正!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
相关资源
最近更新 更多