9

我已经检查了这里的其他问题,但我看不到这个问题。我有一个标签问题。奇怪的是,除了一个之外,所有标签的代码都可以正常工作。当我检查数据集(这很简单)时,一切似乎都很好(一列带有因子变量,另一列带有数字)。

这很奇怪,因为它适用于具有相同结构的其他一些数据。但是,我尝试/检查了所有内容,但无法解决此问题。这是问题所在:

library(ggplot2)
library(ggrepel)

df = data.frame(
  status = c("Oak", "maple", "walnut", "Pine"),
  value = c( 47.54, 37.70, 11.48, 3.28))

ggplot(df, aes(x = "" , y = value, fill = fct_inorder(status))) +
  geom_bar(width = 1, stat = "identity") +
  coord_polar(theta = "y", start = 0 ) +
  scale_fill_brewer(palette = "Set3", direction = -4) +
  geom_label_repel(aes(label = paste0(value, "%")), size=4, show.legend = F, nudge_x = 1) +
  guides(fill = guide_legend(title = "Status")) +
  theme_void()

其中一个标签出现了问题

如果我至少有一个尝试或解释这种奇怪行为的建议,那就太好了。

显然,随着新的 ggplot2 更新,他们在没有提供任何额外位置数据的情况下解决了位置问题,但不知何故,如果由于技术限制而无法使用它,这可能有助于解决此类问题。

4

1 回答 1

8

我认为问题在于geom_bar(或更好geom_col)默认为position = stackgeom_text_repel没有。设置geom_text_repelposition= "stack"将标签放在饼图每个部分的末尾而不是中点。

可以预先计算位置。下面的代码适用于显示的数据,但可能不通用,因为它取决于行的顺序。

library(ggplot2)
library(ggrepel)

df = data.frame(
  status = c("Oak", "maple", "walnut", "Pine"),
  value = c( 47.54, 37.70, 11.48, 3.28))

df2 <- df %>% 
  mutate(
    cs = rev(cumsum(rev(value))), 
    pos = value/2 + lead(cs, 1),
    pos = if_else(is.na(pos), value/2, pos))

ggplot(df, aes(x = "" , y = value, fill = fct_inorder(status))) +
  geom_col(width = 1) +
  coord_polar(theta = "y", start = 0 ) +
  scale_fill_brewer(palette = "Set3", direction = -4) +
  geom_label_repel(aes(y = pos, label = paste0(value, "%")), data = df2, size=4, show.legend = F, nudge_x = 1) +
  guides(fill = guide_legend(title = "Status")) +
  theme_void()
于 2018-09-10T13:22:22.287 回答