繁体   English   中英

如何绘制图表以比较 R 中两个不同数据集的数据

[英]How to draw a graph for comparing data from two different datasets in R

有2个数据集

Forecast=structure(list(sub = c("01.01.01 Automatic switches ARMAT", "01.01.01 Automatic switches ARMAT", 
"01.01.01 Automatic switches ARMAT", "01.01.02 Automatic switches KARAT", 
"01.01.02 Automatic switches KARAT", "01.01.02 Automatic switches KARAT"
), ds = c("01.05.2022", "01.06.2022", "01.07.2022", "01.05.2022", 
"01.06.2022", "01.07.2022"), forecast = c(30696L, 30696L, 30696L, 
1089910L, 1089910L, 1089910L), fct = c(22590L, 29243L, 30521L, 
803535L, 1430316L, 1312260L)), class = "data.frame", row.names = c(NA, 
-6L))

sub是分组变量。 forecast列在月份预测( ds列)。 Fact是真实的数据。 按组分别执行的每个预测(子列)

也是第二个数据集

manager_forecast=structure(list(sud = c("01.01.01 Automatic switches ARMAT", "01.01.01 Automatic switches ARMAT", 
"01.01.02 Automatic switches KARAT", "01.01.02 Automatic switches KARAT", 
"", ""), ds = c("01.06.2022", "01.07.2022", "01.06.2022", "01.07.2022", 
"", ""), manager_forecast = c(76011.04671, 113534.0746, 1802431.458, 
1399089.059, NA, NA)), class = "data.frame", row.names = c(NA, 
-6L))

在这个数据集中相同的结构,但这里有列manager_forecast这是经理认为会卖出多少件。

因此,对于每个组(子),我需要绘制我预测将售出多少件与实际售出多少件(数据集预测)和经理假设(manager_forecast)之间的相关性图表

我想为每个子得到类似这张图的东西(我在 excel 中做了这个) 在此处输入图像描述

每个子获取此类图形并将其保存到C: / 1 / plots文件夹的最简单方法是什么。

感谢您的帮助

您需要根据子和日期合并两个数据帧,然后将 pivot 合并为长格式。 绘图非常简单,按子分面,并进行一些主题调整以获得与 Excel plot 相似的外观:

library(tidyverse)

Forecast %>% 
  left_join(manager_forecast, by = c(sub = 'sud', ds = 'ds')) %>%
  pivot_longer(forecast:manager_forecast) %>%
  mutate(ds = lubridate::mdy(ds)) %>%
  ggplot(aes(ds, value, color = name)) +
  geom_line(size = 1) +
  scale_y_continuous(labels = scales::dollar, name = NULL) +
  scale_color_manual(values = c('dodgerblue', '#FF7820', 'gray95'), name = NULL) +
  facet_wrap(sub~., nrow = 2) +
  labs(x = 'Date') +
  theme_dark(base_size = 16) +
  theme(text = element_text(color = 'gray85'),
        plot.background = element_rect(fill = '#303030'),
        panel.background = element_rect(fill = '#303030'),
        legend.position = 'top',
        legend.background = element_blank(),
        axis.text = element_text(color = 'gray85'),
        legend.key = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank())

ggsave('path/to/my/plot.png')

路径/到/我的/plot.png

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM