gpt4 book ai didi

r - 在 ggplot2 中订购饼图切片

转载 作者:行者123 更新时间:2023-12-04 15:03:41 26 4
gpt4 key购买 nike

我想订购我的饼图标签和切片。我在下面的尝试能够对标签进行排序,但切片仍然是无序的。感谢您的帮助。

enter image description here

data = structure(list(Stage = c("Collecting Applications", "Interview Stages", 
"Offer Accepted", "Offer in Progress", "To Open"), N = c(17L,
30L, 8L, 2L, 65L), Prop = c(14, 25, 7, 2, 53), Label = c("14%",
"25%", "7%", "2%", "53%")), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))

data$Stage = factor(data$Stage, ordered = TRUE,
levels = c("To Open", "Collecting Applications", "Interview Stages", "Offer in Progress", "Offer Accepted"))

library(dplyr)
data = data %>%
mutate(end = 2 * pi * cumsum(N)/sum(N),
start = lag(end, default = 0),
middle = 0.5 * (start + end),
hjust = ifelse(middle > pi, 1, 0),
vjust = ifelse(middle < pi/2 | middle > 3 * pi/2, 0, 1))
data = data[order(data$Stage), ]


library(ggforce)
library(ggplot2)

ggplot(data) +
geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1,
start = start, end = end, fill = Stage)) +
geom_text(aes(x = 1.05 * sin(middle), y = 1.05 * cos(middle), label = Label,
hjust = hjust, vjust = vjust)) +
coord_fixed() +
scale_x_continuous(limits = c(-1.5, 1.4), # Adjust so labels are not cut off
name = "", breaks = NULL, labels = NULL) +
scale_y_continuous(limits = c(-1.2, 1.2), # Adjust so labels are not cut off
name = "", breaks = NULL, labels = NULL) +
theme_void() +
labs(title = paste0("Progress for ", sum(data$N), " Positions"),
fill = NULL) +
scale_fill_brewer(palette = "Blues")

最佳答案

一个简单的修复,顺序数据框行需要在 hjust 和 vjust 突变之前。虽然不能完全确定其背后的原因。如果有人知道,将不胜感激。谢谢!

library(dplyr)
data$Stage = factor(data$Stage, ordered = TRUE,
levels = c("To Open", "Collecting Applications", "Interview Stages", "Offer in Progress", "Offer Accepted"))
data = data[order(data$Stage), ]
data = data %>%
mutate(end = 2 * pi * cumsum(N)/sum(N),
start = lag(end, default = 0),
middle = 0.5 * (start + end),
hjust = ifelse(middle > pi, 1, 0),
vjust = ifelse(middle < pi/2 | middle > 3 * pi/2, 0, 1))



library(ggforce)
library(ggplot2)

ggplot(data) +
geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1,
start = start, end = end, fill = Stage)) +
geom_text(aes(x = 1.05 * sin(middle), y = 1.05 * cos(middle), label = Label,
hjust = hjust, vjust = vjust)) +
coord_fixed() +
scale_x_continuous(limits = c(-1.5, 1.4), # Adjust so labels are not cut off
name = "", breaks = NULL, labels = NULL) +
scale_y_continuous(limits = c(-1.2, 1.2), # Adjust so labels are not cut off
name = "", breaks = NULL, labels = NULL) +
theme_void() +
labs(title = paste0("Progress for ", sum(data$N), " Positions"),
fill = NULL) +
scale_fill_brewer(palette = "Blues")

关于r - 在 ggplot2 中订购饼图切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66537091/

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