gpt4 book ai didi

r - ggplot 的 geom_text() 饼图标签隐藏了 geom_bar() 制作的饼图

转载 作者:行者123 更新时间:2023-12-02 03:47:10 30 4
gpt4 key购买 nike

我使用aggregate(,,FUN =sum)函数构造了以下数据:

    structure(list(Group.1 = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 
1L, 2L, 3L), .Label = c("Black or African American", "White Alone",
"White Alone LR"), class = "factor"), Group.2 = structure(c(1L,
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("bus", "mixed", "rail"
), class = "factor"), x = c(75143.5182835844, 198737.537113379,
46973.6469041183, 46199.2335265697, 128026.568239224, 28933.3028730992,
75876.5845180076, 495166.957025367, 5909.04640985574), pos = c(37571.7591417922,
99368.7685566897, 23486.8234520592, 98243.1350468693, 262750.821232991,
61440.2983406679, 159281.044069158, 574347.583865287, 78861.4729821454
), labe = c(" 75,144", "198,738", " 46,974", " 46,199", "128,027",
" 28,933", " 75,877", "495,167", " 5,909")), class = c("tbl_df",
"tbl", "data.frame"), .Names = c("Group.1", "Group.2", "x", "pos",
"labe"), row.names = c(NA, -9L))

我得到了制作饼图的好代码 herehere ,这导致了这个:

modesplit <- ggplot(data = sums) +
geom_bar( aes(factor(1), y=x, fill=Group.2), stat="identity", position="fill") +
scale_fill_discrete(guide=guide_legend(title="Mode")) +
coord_polar(theta="y") +
facet_grid(.~Group.1, labeller = label_value) +
scale_x_discrete(name=" ", breaks = NULL) +
scale_y_continuous(name=" ", breaks = NULL)
plot(modesplit)

Pie charts good

但是当我尝试添加标签时:

modesplit <- ggplot(data = sums) +
geom_bar( aes(factor(1),y=x,fill=Group.2),stat="identity", position="fill") +
geom_text(aes(,y=pos, label = labe), size =5) +
scale_fill_discrete(guide=guide_legend(title="Mode")) +
coord_polar(theta="y") +
facet_grid(.~Group.1,labeller = label_value) +
scale_x_discrete(name=" ", breaks = NULL) +
scale_y_continuous(name=" ", breaks = NULL) +
plot(modesplit)

饼图的“饼图”消失了: Bad Pie

我已经尝试过:

  1. 去除鳞片
  2. 删除scale_fill_discrete

最佳答案

这是一个规模问题。注释掉 coord_polarscale_y_continuous,然后运行带或不带 geom_text 的代码。 geom_bar 中的 position = "fill" 使之加起来为 1,而您的 pos 值有数万。

这是一个解决方案(编辑,因此它现在将标签很好地放在中间)

library(dplyr)
sums2 = sums %>% group_by(Group.1) %>%
mutate(x_scaled = x / sum(x),
pos_scaled = pos / cumsum(x_scaled) - x_scaled / 2)

modesplit <- ggplot(data = sums2, aes(x = factor(1))) +
geom_bar( aes(y=x_scaled, fill=Group.2), stat="identity", position="stack") +
scale_fill_discrete(guide=guide_legend(title="Mode")) +
coord_polar(theta="y") +
geom_text(aes(y = pos_scaled, label = labe), size =5) +
facet_grid(. ~ Group.1, labeller = label_value) +
scale_x_discrete(name=" ", breaks = NULL) +
scale_y_continuous(name=" ", breaks = NULL)

plot(modesplit)

关于r - ggplot 的 geom_text() 饼图标签隐藏了 geom_bar() 制作的饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30044333/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com