我正在尝试重新创建一个图形,但无法正确定位饼图中标签的位置。
这是我当前的代码:
ggplot(flying63, aes(x = '', y = percentage, fill = baby_on_plane)) +
geom_col(width = 1, position = position_fill()) +
coord_polar('y') +
facet_grid(gender ~ age) +
geom_label_repel(aes(label = sprintf("%.2f%%", percentage)),
position = position_fill(), size = 3, max.time = 8) +
theme(axis.text = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank())
library(tidyverse)
library(ggrepel)
datasets::iris %>%
transmute(age = as.numeric(cut_number(Sepal.Length,3)),
gender = as.numeric(cut_number(Petal.Length,2)),
respond = Species) %>%
mutate(n1 = n(), .by = c(age, gender, respond)) %>%
mutate(n2 = n(), .by = c(age, gender)) %>%
mutate(percentage = 100 * n1/n2, .by = c(age, gender)) %>%
unique() %>%
arrange(age, gender) %>%
ggplot(aes(x = '', y = percentage, fill = respond)) +
geom_col(width = 1, position = position_fill()) +
coord_polar('y') +
facet_grid(gender ~ age) +
theme(axis.text = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank()) +
geom_label_repel(aes(label = sprintf("%.0f%%", percentage)),
position = position_fill(vjust = 0.2), size = 3, max.time = 8,
box.padding = 1)
创建于 2023-12-28,使用 reprex v2.0.2
我捏造了一些数据,这样我就可以解决这个问题。我认为您正在寻找的是
box.padding = ...
论点。您可以使用该值来更改偏移的长度。
flying63 <- tibble(percentage = rep(c(80,7,13),4),
baby_on_plane=rep(c('Not Rude','Somewhat','Very'),4),
gender = sample(c('M','F'),12, replace = T),
age = sample(c('18','30','45','60'),12,replace = T))
ggplot(flying63, aes(x = '', y = percentage, fill = baby_on_plane)) +
geom_col(width = 1, position = position_fill()) +
coord_polar('y') +
facet_grid(gender ~ age) +
geom_label_repel(aes(label = sprintf("%.2f%%", percentage)),
position = position_fill(), size = 3, max.time = 8,
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
box.padding = 1) + # This is the change
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
theme(axis.text = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank())