R语言 创建仅显示一个类别的值的饼图并更改值的位置

lf5gs5x2  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(118)

我想在ggplot2中创建一系列饼图。每个图显示两个类别的百分比(“是”、“否”),但我只想显示“是”的百分比值,并且该值应该相对于整个图居中,而不仅仅是“是”部分本身。问题是我能够局部更改值的位置,即而不是在整个饼图的上下文中。
数据集:

df <- data.frame(Perc = c(78, 94, 99, 22, 6, 1), 
    Source = as.factor(rep(c("Oil", "Solar", "Wind"), 2)),
    Agree = as.factor(c(rep("Yes", 3), rep("No", 3))))

绘图:

ggplot(df, aes(x=" ", y=Perc, group=rev(Agree), fill=Agree)) +
    geom_bar(size = .5, stat = "identity", color = "black") + 
    scale_fill_manual(values = c("grey", "lightgreen")) +
    coord_polar("y", start=0) + 
    geom_text(aes(label = ifelse(Agree=="Yes", paste0(Perc, "%"),""))) +
    facet_grid(~Source) + theme_void() + theme(legend.position = "none", strip.text.x = element_text(size = 9))

现在我得到的图看起来像这样:

我想创造这样的情节:

eqoofvh9

eqoofvh91#

一个选项是将标签的y值设置为50

library(ggplot2)

ggplot(df, aes(x = " ", y = Perc, group = rev(Agree), fill = Agree)) +
  geom_bar(size = .5, stat = "identity", color = "black") +
  scale_fill_manual(values = c("grey", "lightgreen")) +
  coord_polar("y", start = 0) +
  geom_text(aes(y = 50, label = ifelse(Agree == "Yes", paste0(Perc, "%"), ""))) +
  facet_grid(~Source) +
  theme_void() +
  theme(legend.position = "none", strip.text.x = element_text(size = 9))

相关问题