在R中绘制饼图

Pie chart drawing in R

我想绘制如下饼图: Pie

数据集的样本是这样的

structure(list(`Valuation Area` = c("20G5", "20G5", "20G5", "20G5", 
"20G5", "20G5", "20G5", "20G5", "20G5", "20G5", "20G5", "20G5", 
"20G5", "20G5", "20G5"), Backorder = c(15, 6, NA, 7, 5, 14, NA, 
NA, 4, NA, 3, NA, 12, NA, 1), `New higher` = c("yes", "yes", 
"yes", "yes", "yes", "yes", "yes", "no", "yes", "yes", "yes", 
"no", "no", "no", "yes")), row.names = c(NA, -15L), class = c("tbl_df", 
"tbl", "data.frame"))

我的第一步,

library(dplyr)
library(tidyr)
library(ggplot2)

dput(Top_purchasing_2021[1:15,c(1,20,24)]) %>%
    drop_na(Backorder) %>%
    summarise(sum_backorder = sum(`Valuation Area` == "20G5"),
              sum_reduce_safetystock = sum(`New higher` == "yes"),
              sum_increase_safetystock = sum_backorder-sum_reduce_safetystock)

我的第 2 步,

df <-  data.frame(group = c("sum_reduce_safetystock", "sum_increase_safetystock"), value = c(8, 1))
bp <-  ggplot(df, aes(x="", y=value, fill=group)) +
  geom_bar(width=2, stat="identity")
bp
pie <- bp + coord_polar("y", start=0) + labs(title="backorder with safety stock")
pie

可以看出“value=c(8,1)”是我从步骤 1 中得到的。当我将代码更改为下面的代码时,它仍然绘制饼图但显示错误 ” data.frame(group = c("sum_reduce_safetystock", "sum_increase_safetystock") 中的错误: 未找到对象 'sum_reduce_safetystock'"

df <-  data.frame(group = c("sum_reduce_safetystock", "sum_increase_safetystock"), value = c(sum_reduce_safetystock, sum_increase_safetystock))
bp <-  ggplot(df, aes(x="", y=value, fill=group)) +
  geom_bar(width=2, stat="identity")
bp
pie <- bp + coord_polar("y", start=0) + labs(title="backorder with safety stock")
pie

我该如何解决这个问题,或者我能以更好的方式解决这个问题吗?谢谢。

ggplot2 可以为您完成所有计算,只要您有长格式的数据 - 您不需要 summarise 自己。

我会简单地创建您要绘制的两个二进制变量,然后让 geom_bar 进行计算。 ggarrange 来自 ggpubr 然后可以将两个图表排列在一起。

library(dplyr)
library(ggplot2)

# Create binary variables
Top_purchasing_2021 <- Top_purchasing_2021 |> 
  mutate(backorder = ifelse(is.na(Backorder),
                            "Without backorder",
                            "With backorder"),
         aim = ifelse(`New higher` == "yes",
                      "To reduce safety stock",
                      "To increase safety stock"))

# First pie chart
a <- Top_purchasing_2021 |> 
    ggplot(aes(x = "", y = backorder, fill = backorder)) +
    geom_bar(stat = "identity", width = 1) +
    coord_polar("y", start = 0) +
    theme_void() +
    theme(legend.position = "bottom")

# Second pie chart
b <- Top_purchasing_2021 |>
    filter(backorder == "With backorder") |>
    ggplot(aes(x = "", y = aim, fill = aim)) +
    geom_bar(stat = "identity", width = 1) +
    coord_polar("y", start = 0) +
    theme_void() +
    scale_fill_manual(values = c("coral4", "coral2")) +
    theme(legend.position = "bottom")

# Combine into one
ggpubr::ggarrange(a, b)

注意 - 饼图通常不是最好的数据可视化工具(这可能是它们在 ggplot 中实施起来不是很简单的原因)。有关详细信息,请参阅 here