我有一個資料框 sush ;
標簽
Groups Cat1 Cat2
1 A 4 2
2 B 0 0
3 C 1 1
4 D 2 0
并從該資料框中,我可以設法撰寫以下圖:
ggplot(tab, aes(x=factor(1), y=factor(Cat1),fill=factor(Cat1)))
geom_bar(stat='identity',colour="white",size=0.7,width=1)
coord_polar(theta='y') theme_inset() theme(legend.position = c(0.10, 0.8))

我想知道是否可以通過在每個區域周圍添加比例黑色邊框來包含Cat2Groups列值。
在這樣的情節中,我應該得到類似的東西
如您所見,由于 2/4 (50%)Cat2存在groupA,我只為 周圍的一半邊框著色 groupA,并且由于 1/1 (100%)Cat2存在groupC,我為 周圍的所有邊框著色groupC。而且由于GroupD0 中的數字Cat2,它根本沒有為邊框著色。

如果它可以幫助,這是表的 dput 格式:
structure(list(Groups = c("A", "B", "C", "D"), Cat1 = c(4L, 0L,
1L, 2L), Cat2 = c(2L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA,
-4L))
uj5u.com熱心網友回復:
實作所需結果的一個選項是首先創建第二個資料框,其中還包括非“類別 2”值的數量。然后可以使用第二個資料框在您的餅圖周圍繪制一個甜甜圈,在其中我使用"transparent"顏色填充 Non-Cat2 類別。
為了完成這項作業,我們必須添加一個新的分組列作為您的Groups列和新的 Cat2/Non-Cat2 列的互動。我還切換到連續的 x 刻度,這樣可以輕松地將甜甜圈很好地“包裹”在餡餅周圍。
library(ggplot2)
library(dplyr)
library(tidyr)
tab1 <- tab |>
mutate(nonCat2 = Cat1 - Cat2) |>
pivot_longer(c(Cat2, nonCat2), names_to = "Groups1", values_to = "Cat2") |>
mutate(Groups = interaction(Groups, Groups1, lex.order = TRUE))
pal <- scales::hue_pal()(4)
names(pal) <- c("A", "B", "C", "D")
pal <- c(pal, c(Cat2 = "black", nonCat2 = "transparent"))
ggplot()
geom_col(data = tab, aes(x = 1, y = Cat1, fill = Groups), color = "white")
geom_col(data = tab1, aes(x = 1.5, y = Cat2, fill = Groups1, group = Groups), width = .1, color = "white")
scale_fill_manual(values = pal, breaks = LETTERS[1:4])
coord_polar(theta = "y")
theme_void()
theme(legend.position = c(0.10, 0.8))

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/488002.html
上一篇:不能與cowplot包左對齊
