我想畫一個像下面這樣的餅圖: 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
我該如何解決這個問題,或者我可以以更好的方式做到這一點嗎?謝謝你。
uj5u.com熱心網友回復:
ggplot2只要您擁有長格式的資料,就可以為您完成所有計算 - 您不需要summarise自己。
我只需創建您要繪制的兩個二進制變數,然后geom_bar進行計算。ggarrangefromggpubr然后可以將兩個圖表排列在一起。
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)
NB - 餅圖通常不是最好的資料可視化工具(這可能是為什么它們不是很容易實作的原因ggplot)。請參閱此處了解更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462741.html
下一篇:如何在ggplot中為變數分組?
