2

我想出了如何创建一个帕累托图,但问题是如果我有一个表格需要计算和显示帕累托聊天,我就卡住了。

dt <- data.table( YEAR = c("2001", "2000", "2001", "2001","1999", "2000", "2000", "1999", "1999"),
                Col1=sample(0:30, 8, rep=TRUE),
                Col2 =sample(0:45, 8, rep=TRUE),
                col33 =sample(0:60, 8, rep=TRUE)
)

例如,我会为每个 Col 变量提供一个图表,最好一起显示。

我计算一张图表的代码是:

Col1_gain <- dt[YEAR=="1999"][order (-Col1)]
Col1_gain<-Col1_gain[, !c("Col2","Col33")]
Col1_gain <- Col1_gain[, `:=` (paret=(cumsum(Col1_gain$Col1))*100/sum(Col1_gain$Col1), cum=(cumsum(Col1_gain$Col1)))]
Col1_gain$ID <- seq.int(nrow(Col1_gain))
Col1_pareto <- ggplot(Col1_gain, aes (x=ID/nrow(Col1_gain)))+ geom_line(aes(y=paret), size=1, color="firebrick")
Col1_pareto
4

1 回答 1

3

根据我对绘制一个帕累托图的代码的理解,您正在隔离一年,然后绘制以百分比表示的累积总和。

因此,如果您想为多年和多列执行此操作,您首先需要将数据表转换为更长的格式(这里我使用pivot_longerfromtidyr但您可以使用 from 做同样的事情meltdata.table

然后,我将按年份和分类变量“Var”(包含 Col1、Col2、...)对您的数据进行分组,并将该值表示为总数的百分比和百分比的累积总和。我还创建了一个基本上是行号的计数,以便将其用作 x 轴。

最后,我使用这些新变量制作了条形图和线条。我使用 . 分隔“年” facet_wrap。总之,你可以这样写:

dt %>% pivot_longer(., -YEAR, names_to = "Var", values_to = "Val") %>%
  group_by(YEAR, Var) %>%
  arrange(desc(Val), .by_group = TRUE) %>%
  mutate(CumS = cumsum(Val), Count = row_number()) %>%
  mutate(CumS2 = CumS*100 / sum(Val)) %>%
  mutate(Val_Percent = Val*100/sum(Val)) %>%
  ggplot(aes(x = as.factor(Count), y = Val_Percent, fill = Var))+
  geom_col(position = position_dodge())+
  facet_wrap(.~YEAR)+
  geom_line(aes(y = CumS2, group = Var, color = Var), position = position_dodge(.9))+
  theme(axis.text.x = element_blank(),
        axis.title.x = element_blank(),
        axis.ticks.x = element_blank())

在此处输入图像描述

或者,如果您想获得每个“Col”和每个“Year”的帕累托图,您可以执行完全相同的操作,然后使用 offacet_grid代替facet_wrap

dt %>% pivot_longer(., -YEAR, names_to = "Var", values_to = "Val") %>%
  group_by(YEAR, Var) %>%
  arrange(desc(Val), .by_group = TRUE) %>%
  mutate(CumS = cumsum(Val), Count = row_number()) %>%
  mutate(CumS2 = CumS*100 / sum(Val)) %>%
  mutate(Val_Percent = Val*100/sum(Val)) %>%
  ggplot(aes(x = as.factor(Count), y = Val_Percent, fill = Var))+
  geom_col(position = position_dodge())+
  facet_grid(Var~YEAR)+
  geom_line(aes(y = CumS2, group = Var, color = Var), position = position_dodge(.9))+
  theme(axis.text.x = element_blank(),
        axis.title.x = element_blank(),
        axis.ticks.x = element_blank())

在此处输入图像描述

它回答了你的问题吗?

于 2020-01-30T18:27:44.867 回答