如何使用ggplot2 :: scale_x_yearqtr

问题描述 投票:0回答:1

我想在条形图中按季度绘制某些实例。我使用zoo::yearqtr类型对四分之一区进行分类,但数据框是一个小标题,而不是动物园。我以为ggplot2::scale_x_yearqtr()会给我一个漂亮的情节,但我发生了变化。在最上面的示例中,我使用as.factor来获得所需的外观,但是由于时间是连续的,因此这似乎是一种不好的做法,而且还存在手动计算合理间隔的麻烦。

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.6.3
library(zoo)
#> 
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#> 
#>     as.Date, as.Date.numeric
date <- c(2016.00,2016.50, 2016.50, 2016.75, 2017.75, 2019.00, 2016.00, 2016.25,
          2016.50, 2016.75, 2017.00, 2017.25, 2017.50, 2017.75, 2018.00, 2018.25,
          2018.50, 2018.75, 2019.00, 2019.25, 2019.50, 2019.75)

count <-  c(3, 3,  4,  6,  3,  3,  3, 10,  2,  6,  4,
            7,  4,  4,  3,  5,  2,  5,  6,  4,  6,  3)

fill <- c("polka","waltz","polka","polka","waltz","samba","other","other","other",
          "other","other","other","other","other","other","other","other","other",
          "other","other","other","other")

# dates are duplicated (but with different events) and not ordered
df0 <- data.frame(date,count,fill)

ggplot(df0,aes(factor(as.numeric(date)),count,fill=fill)) + geom_col() + 
  scale_x_discrete(breaks=sort(unique(round(as.numeric(df0$date)))))

proper bar plot

可爱。现在,让date列成为yearqtr类型,并使用scale_x_yearqtr获得漂亮的x轴。

df1 <-  df0
df1$date <- zoo::as.yearqtr(df1$date)
ggplot(df1,aes(date,count,fill=fill)) + geom_col() + 
  scale_x_yearqtr()

mutant plot

哇!那是一个丑陋的突变体!问题的根源不是yearqtr。如果我们不将numeric日期转换为yearqtr,则会得到相同的结果。问题是我假设scale_x_yearqtr会理解该怎么做。是否有一种不求助于as.factor()而获得我要寻找的x轴的正确方法?

我想在条形图中按季度绘制某些实例。我使用zoo :: yearqtr类型对宿舍进行分类,但数据框是一个小标题而不是Zoo。我认为ggplot2 :: ...

r ggplot2 zoo
1个回答
0
投票

我想您只需要

© www.soinside.com 2019 - 2024. All rights reserved.