我正在將多個檔案分別讀入一個資料框中。例如“蘋果”、“橙子”和“檸檬”的檔案。這些檔案(=資料幀)中的每一個都包含如下資料:
Def Q1-2021 Q2-2021 Q3-2021 ID
1 price 15 17 9 apples
2 stock 1270 3575 175 apples
3 revenue 57866 66287 21755 apples
4 profit 22156 34187 9253 apples
還有幾個季度的資料,但你明白了。
現在我想制作一個圖表,將所有資料框(即蘋果、橙子、檸檬等)的價格顯示為折線圖。
我正在考慮將所有資料幀系結在一起,但由于并非所有產品都有每個季度的資料,所以這行不通。
現在我被困住了,不知道如何進一步。有人可以幫我嗎?
uj5u.com熱心網友回復:
如果您將資料轉換為“長”格式,那么將很容易rbind根據需要進行繪制。我只是為橙子編了一些資料來幫助說明。
首先,我會將每個都data.frame放入 alist然后你可以同時對所有操作進行操作,然后組合apply()。purrr::map()
重新格式化您的日期資訊也可能有助于更好地繪制它,因此您會看到我把年放在季度之前,但這里還有許多其他不錯的選擇,具體取決于您的實際資料結構和最終目標。
最后,您只提到了繪制價格,但我在這里展示了如何繪制所有不同的值型別,以備不時之需。如果沒有,您可以取消注釋filter()剛到的行price。
library(tidyverse)
apples <- structure(list(Def = c("price", "stock", "revenue", "profit"), `Q1-2021` = c(15L, 1270L, 57866L, 22156L), `Q2-2021` = c(17L, 3575L, 66287L, 34187L), `Q3-2021` = c(9L, 175L, 21755L, 9253L), ID = c("apples", "apples", "apples", "apples")), class = "data.frame", row.names = c(NA, -4L))
oranges <- structure(list(Def = c("price", "stock", "revenue", "profit"), `Q2-2021` = c(14, 2860, 53030, 27350), `Q3-2021` = c(5, 105, 13053, 5552), ID = c("oranges", "oranges", "oranges", "oranges")), class = "data.frame", row.names = c(NA, -4L))
l <- list(apples = apples,
oranges = oranges)
merged_data <- l %>%
map_dfr(~.x %>%
pivot_longer(starts_with("Q"), names_to = "quarter") %>%
separate(quarter, into = c("quarter", "year")) %>%
unite("date", year, quarter))
merged_data
#> # A tibble: 20 × 4
#> Def ID date value
#> <chr> <chr> <chr> <dbl>
#> 1 price apples 2021_Q1 15
#> 2 price apples 2021_Q2 17
#> 3 price apples 2021_Q3 9
#> 4 stock apples 2021_Q1 1270
#> 5 stock apples 2021_Q2 3575
#> 6 stock apples 2021_Q3 175
#> 7 revenue apples 2021_Q1 57866
#> 8 revenue apples 2021_Q2 66287
#> 9 revenue apples 2021_Q3 21755
#> 10 profit apples 2021_Q1 22156
#> 11 profit apples 2021_Q2 34187
#> 12 profit apples 2021_Q3 9253
#> 13 price oranges 2021_Q2 14
#> 14 price oranges 2021_Q3 5
#> 15 stock oranges 2021_Q2 2860
#> 16 stock oranges 2021_Q3 105
#> 17 revenue oranges 2021_Q2 53030
#> 18 revenue oranges 2021_Q3 13053
#> 19 profit oranges 2021_Q2 27350
#> 20 profit oranges 2021_Q3 5552
merged_data %>%
# filter(Def == "price") %>% # this will just plot price
ggplot(aes(date, value, color = ID))
geom_point()
geom_line(aes(group = ID))
facet_wrap(~Def, scales = "free_y")

創建于 2022-11-21,使用reprex v2.0.2
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/537772.html
標籤:r数据框图表2
下一篇:Rggplot2-為什么geom_boxplot忽略美學“ymin”、“lower”、“middle”、“upper”、“ymax”?
