我怎样让ggplot每天打破x轴?

时间:2017-08-25 12:46:15

标签: r date time-series bar-chart

我想得到一个每天显示一定数量的条形图。然而,ggplot并没有显示出这些日子,而是每个月的总结。我怎样让ggplot每天打破x轴?

这是我正在使用的代码:

ggplot(aes(x=d.data$a, y= d.data$b), data = d.data) +
  geom_bar(stat = 'identity', position = 'dodge') +
  scale_x_date(breaks = '1 day') +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

运行上面的代码后,会出现以下错误:Error in strsplit(unitspec, " ") : non-character argument

以下数据用作输入:

d.data <- structure(list(a = structure(c(16771, 16772, 16773, 16774, 16776, 
    16777, 16780, 16781, 16782, 16784, 16785, 16787, 16788, 16789, 
    16790, 16791, 16792, 16796, 16797, 16798, 16799, 16800, 16801, 
    16802, 16803, 16804, 16805, 16806, 16807, 16808, 16809, 16810, 
    16811, 16812, 16813, 16814, 16815, 16816, 16817, 16818, 16819, 
    16820, 16821, 16822, 16823, 16824, 16825, 16826, 16827, 16828, 
    16829, 16830, 16831, 16832, 16833, 16834, 16835, 16836, 16837
    ), class = "Date"), b = c(5613L, 1374L, 6179L, 2913L, 6628L, 
    3265L, 1763L, 10678L, 7308L, 8686L, 11805L, 4988L, 6584L, 11847L, 
    271L, 8125L, 11227L, 6969L, 8407L, 5083L, 8188L, 10500L, 4592L, 
    8691L, 1121L, 1150L, 3154L, 11724L, 6059L, 2573L, 10244L, 1008L, 
    10938L, 7356L, 1931L, 5182L, 1541L, 10449L, 9948L, 2418L, 10384L, 
    11416L, 8994L, 10652L, 6231L, 3777L, 6079L, 10041L, 10922L, 7410L, 
    1695L, 10890L, 390L, 5635L, 6882L, 6892L, 2807L, 4472L, 5696L
    )), .Names = c("a", "b"), row.names = c(NA, -59L), class = "data.frame")

3 个答案:

答案 0 :(得分:5)

使用您的数据,首先需要确保您的日期列来自班级POSIXct,然后您可以使用下面的ggplot代码:

d.data$a <- as.POSIXct(d.data$a)

ggplot(aes(x = a, y = b), data = d.data) +
  geom_bar(stat = 'identity', position = 'dodge') +
  scale_x_datetime(date_breaks = "1 day") +     ### changed
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

这产生以下图:

enter image description here

答案 1 :(得分:0)

虽然您可以在breaks中指定scale_x_date(),但为了使用格式指定每日休息时间,正确的参数为date_breaks。您可以通过运行scale_x_date()?scale_x_date的帮助中查看其使用示例。

因此,您的代码应为:

ggplot(aes(x=a, y= b), data = d.data) +
  geom_col(position = 'dodge') +
  scale_x_date(date_breaks = '1 day') +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

答案 2 :(得分:0)

似乎命令已更改*请参阅(ggplot2 scale x date?):看来参数已更改为date_breaks