首页 > 解决方案 > ggplot2 geom_text 在饼图中的位置

问题描述

我正在用 ggplot2 绘制饼图,并成功地将百分比标签置于每个切片的中心

library(dplyr) 
library(ggplot2)
library(ggpubr)
library("readxl")
df <- read_excel("Radiocomp.xlsx")

df$Pattern <- factor(cc$Pattern)
str(cc)

GGO <- ggplot(data=df, aes(x = "", y = GGO, fill = Pattern)) +
  geom_bar(stat="identity", color = "white") +
  geom_text(aes(label = paste0(GGO, "%")), position = position_stack(vjust = 0.5)) +
  coord_polar("y") +
  theme_void()

GGO

饼形图

我尝试将百分比标签放在饼图之外以提高可读性

有什么推荐吗?

谢谢

标签: ggplot2pie-chartgeom-text

解决方案


这可以通过将x美学设置在内部来实现geom_text,例如x = 1.6将标签放在派的外面。

library(ggplot2)
library(dplyr)

# example data
mpg1 <- mpg %>% 
  count(class) %>% 
  mutate(pct = n / sum(n))

ggplot(mpg1, aes(x = "", y = pct, fill = class)) +
  geom_bar(stat = "identity", color = "white") +
  geom_text(aes(x = 1.6, label = scales::percent(pct, accuracy = .1)), position = position_stack(vjust = .5)) +
  coord_polar("y") +
  theme_void()

reprex 包(v0.3.0)于 2020-06-03 创建


推荐阅读