如何调整饼图中的文本位置/使用极坐标

时间:2021-03-24 08:57:06

标签: r ggplot2 geom-text

我想调整饼图上的文字。

我想把值放在饼图每一边的中间。

我尝试过使用 hjust、vjust,并尝试使用其他功能等。但没有奏效。

这是我的数据和状态。谢谢你的帮助。

k<-data.frame(group=c('alpha','bets'),value=c(0.512,0.488))

ggplot(k,aes(x="",y=value,fill=group))+

  geom_bar(width=1,stat="identity")+

  coord_polar("y")+

  geom_text_repel(aes(label=round(value,3)))

2 个答案:

答案 0 :(得分:1)

极坐标图通常在笛卡尔坐标中更容易调试。您可能需要 position = position_stack(vjust = 0.5) 作为文本几何体。

library(ggplot2)
k <- data.frame(group = c("alpha", "bets"), value = c(0.512, 0.488))

ggplot(k, aes(x = "", y = value, fill = group)) +
  geom_col(width = 1) +
  coord_polar("y") +
  geom_text(aes(label = round(value, 3)), position = position_stack(vjust = 0.5))

reprex package (v1.0.0) 于 2021 年 3 月 24 日创建

答案 1 :(得分:0)

我会为文本标签创建一个单独的数据框并手动设置坐标。

library(ggplot2)
library(ggrepel)
k <- data.frame(group = c("alpha", "bets"), value = c(0.512, 0.488))

data_text <- data.frame(x = 1, y = c(.75, .25), value = k$value)

ggplot(k, aes(x = "", y = value, )) +
  geom_bar(aes(fill = group), width = 1, stat = "identity") +
  coord_polar("y") +
  geom_text(data = data_text, aes(x = x, y = y, label = round(value, 3)))

reprex package (v1.0.0) 于 2021 年 3 月 24 日创建