我正在尝试在下面绘制我的
DATA
的饼图,但标签和颜色似乎放错了位置。
是否有任何特定设置来对齐标签和颜色?
library(ggrepel)
DATA <- read.table(header=T, text="
EthnicCd SchoolYear n_RCA percent csum pos
Hispanic 2324 4520 50% 9117 6857
Asian 2324 1800 20% 4597 3697
White 2324 1737 19% 2797 1928.
Black 2324 447 5% 1060 836.
Pacific 2324 395 4% 613 416.
Multiracial 2324 203 2% 218 116.
AmerInd 2324 15 0% 15 7.5")
ggplot(DATA, aes(x="", y=n_RCA, fill=EthnicCd)) +
geom_bar(stat="identity", width=.008, color="white") +
coord_polar("y", start = 5.5) +
theme_void() +
scale_fill_brewer(palette="Set1")+
guides(fill = guide_legend(title = bquote(~bold("Ethnic Background"))))+
geom_label_repel(aes(y = pos, label = paste0(n_RCA,"\n(",percent,")")),
size = 3, nudge_x = .004, nudge_y=4,
show.legend = FALSE)
首先,您为两层提供不同的 y 值。其次,条形图默认是堆叠的,但标签不是。我们需要为标签提供
position
以匹配条形的堆叠,并且我们可以使用 justification 参数将标签放置在条形的中间:
ggplot(DATA, aes(x = 1, n_RCA, fill=EthnicCd)) +
geom_col(width = 1, color="white") +
geom_label_repel(
aes(x = 1.49, y = n_RCA, label = paste0(n_RCA,"\n(",percent,")")),
position = position_stack(vjust = 0.5),
size = 3,# nudge_x = .004, nudge_y=4,
show.legend = FALSE
) +
coord_polar("y", start = 5.5) +
theme_void() +
scale_fill_brewer(palette="Set1")+
guides(fill = guide_legend(title = bquote(~bold("Ethnic Background"))))
我将标签的 x 位置设置为 ~1.5,以便将它们放置在饼图的外部。这是因为我为条形设置了
x = 1
,并将条形“宽度”设置为 1,因此其范围从 0.5 到 1.5。