【问题标题】:Strange behaviour of GGPLOT when x-axis corresponds Datex轴对应日期时GGPLOT的奇怪行为
【发布时间】:2022-01-07 21:30:01
【问题描述】:

我下面有GGPLOT

library(zoo)
library(quantmod)
library(ggplot2)
Data = data.frame('class' = c(rep(c('a', 'b', 'c'), 8), c('a', 'b')), 'Date' = as.yearqtr(rep(c('2021 Q4', '2022 Q1', '2022 Q2', '2022 Q3', '2022 Q4', '2023 Q1', '2023 Q2', '2023 Q3', '2023 Q4' ), each = 3))[-27], 'Value' = 1:26)
ggplot(Data, aes(x = Date, y = Value, fill = class)) +
    geom_bar(stat = 'identity', position = 'dodge', width = 0.1)

有了这个,我得到了下面的情节:

如您所见,第一个日期从绘图窗口中流出。

任何提示为什么会发生这种情况以及如何纠正这种情况都会非常有帮助。

另外,我怎样才能获得所有日期的x-axis 标记而不是替代日期?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    问题来自使用as.yearqtr 解释here

    ggplot(Data, aes(x = Date, y = Value, fill = class)) +
      geom_bar(stat = 'identity', position = 'dodge', width = 0.1) +
      scale_x_yearqtr(breaks = seq(from = min(Data$Date), to = max(Data$Date), by = 0.25), format = "%YQ%q")
    

    【讨论】:

      【解决方案2】:

      如果您使用factor(Date) 将日期作为因素,您将解决您的两个问题。 你会注意到你得到了非常瘦的酒吧。只需将geom_bar() 中的width 参数更改为0.5

      ggplot(Data, aes(x = factor(Date), y = Value, fill = class)) + geom_bar(stat = 'identity', position = 'dodge', width = 0.5)

      Link to output plot

      【讨论】:

      • 谢谢。但我会尽量避免将日期更改为因素,因为如果我有很多日期,那么情节看起来会很混乱
      • 好点,感谢您的评论
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      • 2020-02-05
      • 1970-01-01
      相关资源
      最近更新 更多