【问题标题】:ggplot2 geom_text position in pie chartggplot2 geom_text 在饼图中的位置
【发布时间】:2020-06-04 03:39:04
【问题描述】:

我正在用 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

Pie chart

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

有什么推荐吗?

谢谢

【问题讨论】:

    标签: ggplot2 pie-chart geom-text


    【解决方案1】:

    这可以通过在geom_text 中设置x 美学来实现,例如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 package (v0.3.0) 于 2020 年 6 月 3 日创建

    【讨论】:

    • 非常感谢您的宝贵意见。在 geom_text 中添加 x 美学几乎可以工作,但是低于 2 的 x 值会导致甜甜圈和移位的标签,而高于 2 的 x 值会将标签放置在图表之外太远。
    • 嗨@xray_mash。它就是这样儿的。 (; 但据我所知,这是迄今为止最简单的解决方案。有关绘制饼图和设置标签的冗长讨论,请参阅例如stackoverflow.com/questions/16184188/…。顺便说一句:定位标签总是需要一些手动工作和调整。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    相关资源
    最近更新 更多