如何使用函数facet_wrap()在R中的ggplot2中绘制时间序列数据

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

问题

我正在做一个项目,需要使用ggplot2来绘制时间序列数据。

我尝试绘制每年每月灯泡的频率,但尺寸看起来不准确,x 轴仅表示一月,标题“年份”比条形大,您几乎看不到。

有谁知道如何修改 R 代码以使其看起来更像期望的结果?

非常感谢您能提供帮助。

我的数据框示例

   year     month Number_Daffodils Frequency_New_Bulbs       date n_month
1  2012   January                1                   7 2012-01-01       1
2  2012  February                8                  59 2012-02-01       2
3  2012     April               18                 144 2012-04-01       4
4  2012       May               21                 193 2012-05-01       5

这就是我到目前为止所做的:

 #Note that %b represents the abbreviated month which will be plotted as labels on the x-axis.
 #Use the column 'date' that contains month of the year as a class of type date


Year_Group_Size<-dat_Ds %>% 
                            ggplot(aes(x = date, y = Frequency_New_Bulbs)) +
                            geom_bar(stat = "identity", fill = "darkorchid4") +
                            facet_wrap(~ year, ncol = 3) +
                            labs(title = "Montly Total Estimated Group Size Per Month Per Year",
                            subtitle = "Data plotted by year",
                            y = "Estimated Group Size",
                            x = "Month") + theme_bw(base_size = 15) +
                            scale_x_date(date_labels = "%b")

虚拟数据框

tibble(
  Month = sample(month.name, 120, replace = TRUE),
  Year = sample(2012:2024, 120, replace = TRUE),
  Date = Sys.Date(), 120, replace = TRUE,
  Number_Daffodils = sample(1:5, 120, replace = TRUE)
  ) 

输出

enter image description here

所需输出
enter image description here

r ggplot2 plot dplyr time-series
1个回答
0
投票

在绘图之前总结数据,试试这个例子:

library(ggplot2)
library(dplyr)

dat_Ds <- data.frame(
  Month = sample(month.name, 120, replace = TRUE),
  Year = sample(2012:2024, 120, replace = TRUE),
  Date = Sys.Date() + 1:120,
  Number_Daffodils = sample(1:5, 120, replace = TRUE)) 

dat_Ds_sum <- dat_Ds %>% 
  mutate(myMonth = factor(substring(Month, 1, 3), month.abb)) %>% 
  group_by(Year, myMonth) %>% 
  summarise(mySum = sum(Number_Daffodils))

ggplot(dat_Ds_sum, aes(x = myMonth, y = mySum)) +
  geom_bar(stat = "identity", fill = "darkorchid4") +
  facet_wrap(~ Year, ncol = 3)

enter image description here

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