在 r 中按季度绘制具有不同值和类别的数据框作为直方图

Plot a dataframe with different values and categories on quarterly basis in r as a histogram

我的数据集有问题,我想创建一个直方图来显示每个季度的观察分布。观察分为 3 类,应每季度显示一次。 不幸的是,我还没有发现它是如何工作的。对于“正常”图,我通过命令“points”添加了相应的观察点,但我不太清楚这如何与直方图一起使用。非常感谢任何帮助!

这是我的数据样本(实际上有大约 20 年的观察及其类别):

            date    n           Categorie1 Categorie2 Categorie3
         2015 Q1    67                5          2          1
         2015 Q2    71                3          4          2
         2015 Q3    69                2         10         11
         2015 Q4    62                1          0          0 
         2016 Q1    69                2          2          1
         2016 Q2    61                3          5          0
         2016 Q3    63                3          2          7
         

变量“日期”的格式为 'yearqtr'。

我使用以下代码生成了正常的情节:

> plot(df23$date,df23$Categorie1 , col = "red", pch = 16, xlab="Quarter",
> ylab="Occurencies")
>     points(df23$date,df23$Categorie2 , col = "blue", pch = 16)
>     points(df23$date,df23$Categorie3 , col = "green", pch = 16)

所以我得到了一个图表,但我不知道如何获得每个季度不同类别的直方图。

你能帮我创建不同类别和不同季度的直方图吗?

非常感谢!

这是我的输出(df23):

>  dput(df23)
structure(list(date = structure(c(2015, 2015.25, 2015.5, 2015.75, 
2016, 2016.25, 2016.5), class = "yearqtr"), n = c(67, 71, 69, 
62, 69, 61, 63), Categorie1 = c(5, 3, 2, 1, 2, 3, 3), Categorie2 = c(2, 
4, 10, 0, 2, 5, 2), Categorie3 = c(1, 2, 11, 0, 1, 0, 7)), row.names = c(NA, 
7L), class = "data.frame")

我们可以使用 tidyverse 方法

library(ggplot2)
library(tidyr)
library(dplyr)
library(zoo) # format "yearqtr"


df23 %>% 
  pivot_longer(
    starts_with("Categorie"), 
    names_to = "Categorie",
    names_pattern = "Categorie(\d+)"
  ) %>% 
  ggplot(aes(x = date, y = value, fill = Categorie)) + 
  geom_bar(position = "dodge", stat = "identity")

得到

数据

df23 <- structure(list(date = structure(c(2015, 2015.25, 2015.5, 2015.75, 
2016, 2016.25, 2016.5), class = "yearqtr"), n = c(67, 71, 69, 
62, 69, 61, 63), Categorie1 = c(5, 3, 2, 1, 2, 3, 3), Categorie2 = c(2, 
4, 10, 0, 2, 5, 2), Categorie3 = c(1, 2, 11, 0, 1, 0, 7)), row.names = c(NA, 
-7L), class = c("tbl_df", "tbl", "data.frame"))

Martin Gal 的方法非常好。这是另一种方法:

  1. tidyrtidyverse
  2. 中为您带来 pivot_longer 的长格式数据
  3. 由于您的日期列已经很好,您可以使用它 as.factor 而不使用 date 格式(否则请参阅 Martin Gal 的解决方案)
  4. 您也可以使用 geom_col
library(tidyverse)

df23 %>% 
    pivot_longer(
        cols = -c(date, n),
        names_to = "Categorie"
    ) %>% 
    ggplot(aes(x = factor(date), y = value, fill = Categorie)) + 
    geom_col(position = "dodge")