r-在绘制和向条形图添加标签之前重塑数据帧



我正试图重塑我的数据集(代表资产负债表(,以便绘制每个账户的演变图。对于再现性,以下是我的数据集结构:

structure(list(intitule = c("CA sejours", 
"garanties", "+Chiffre d'Affaires hôtelier", "Recettes annexes", 
"=TOTAL CA", "Achats médicaux"
), annee_2019 = c(58523L, 0L, 2474L, 3933L, 64930L, 16532L), 
annee_2020 = c(49751L, 9396L, 2104L, 2808L, 64059L, 15395L
), annee_2021 = c(58681L, 5303L, 2253L, 3059L, 69296L, 15455L
), budget_2021 = c(65327L, 0L, 3653L, 3335L, 72315L, 16115L
), `rapport_21/20` = c("1,17949388", "0,564389102", "1,07081749", 
"1,089387464", "1,081752759", "1,003897369"), en_pourcentage = c("17,95%", 
"-43,56%", "7,08%", "8,94%", "8,18%", "0,39%")), row.names = c(NA, 
6L), class = "data.frame")

我想绘制几个账户的演变图(在"intitule"列中表示(,这是我必须转换我的数据集。

我试过这个:

library(dplyr)
library(tidyr)
test <- analytique[,-(6:7)] |> 
as_tibble() |> 
pivot_longer(cols = -intitule,
names_to = "date",
values_to = "value") |> 
pivot_wider(names_from = intitule,
values_from = value) |> 
arrange(date)

然而,它并没有给我想要的输出来绘制进化图(例如,绘制"CA sejours"从2019年到2021年的进化图(。以下是我想要的产出的结构(重要的是,"初始"行保持相同的顺序,因为它是资产负债表:因此是2019年的资产负债表,低于2020年的资产资产负债表等(:

intitule        value          year
CA sejours       58523         2019
garanties        0             2019

最后,关于绘图,我还有另一个问题:即使在使用geom_text时,我似乎也无法将标签放在条形图的顶部(因为当我这样做时,大多数时候,由于条形图的高度并不都相同,标签要么在条形图顶部的上方,要么略低于条形图顶部(。

谢谢你的帮助!

Pivot longer有一种处理嵌入数据的列名的方法,使用前面进一步解释的name to参数中的.values来实现我认为您正在寻找的结果。

library(tidyverse)
test <-  analytique[,-(5:7)] %>% 
as_tibble()  %>%  
pivot_longer(cols = -intitule,
names_to = c(".value", "Year"),
names_sep = "_") %>% 
rename(Value=annee)

然后,您可以绘制它,并通过指定与geom_col相同的x和y将标签放在条形图的顶部,并指定position dodge参数将它们放在每个单独列的顶部(假设您希望将每年的所有initule放在一起(。

test %>% ggplot() +
geom_col(aes(Year, Value, fill = intitule), position = "dodge") +
geom_text(
aes(Year, Value, label = Value, group = intitule),
position = position_dodge(width = .9),
vjust = -0.5
)

绘制图形的其他选项是每年一起使用initules和不同的条形图:


test %>% ggplot() +
geom_col(aes(intitule, Value, fill = Year), position = "dodge") +
geom_text(
aes(intitule, Value, label = Value, group = Year),
position = position_dodge(width = .9),
vjust = -0.5
)

或贴面

test %>% ggplot() +
geom_col(aes(Year, Value), position = "dodge") +
geom_text(
aes(Year, Value, label = Value, group = Year),
position = position_dodge(width = .9),
vjust = -0.5
)+facet_wrap(~intitule)

最新更新