在ggplot2饼图中移动标签

Move labels in ggplot2 pie graph

我从 How to avoid label overlap in pie chart 得知我可以使用 ggrepel 让标签在饼图中不重叠。我希望有不到 7% 的百分比移到外面,并且有 7% 或更多的百分比移到他们的馅饼上。有什么想法吗?

library( ggrepel )
library( ggplot2)
    library( dplyr)
    library( scales )
    library( reshape )

    y <- data.frame( 
            state = c( "AR" ) , 
            ac = c( 0.43 ) , 
            man = c( 0.26 ) , 
            ltc = c( 0.25 ) , 
            care = c( 0.05 ) , 
            dsh = c( 0.01 ) 
            )

    y2 <- melt( y , id.var="state" )


    test <- ggplot( y2 , aes( x=1 , y=value , fill=variable )) +
                geom_bar( width = 1 , stat = "identity" ) +
                geom_text_repel( aes( label = paste( y2$variable , percent( value )) ) , position = position_fill( vjust = 0.5 ) , color="white" , size=5 ) +
                coord_polar( "y" , start = 0 ) + 
                scale_fill_manual( values=c( "#003C64" , "#0077C8" , "#7FBBE3" , "#BFDDF1" , "#00BC87" ) )

    test

所以在这个例子中,1% 和 5% 会在灰色区域。

这绝不是优雅的,但它可能提供您正在寻找的东西。这种方法涉及计算标签的位置(yvalue 中的中点),并使用不同的 x 位置和 nudge_x 用于带有段的外部标签。也许这会给你一些工作的想法?

library( ggrepel )
library( ggplot2)
library( dplyr)
library( scales )
library( reshape )

y <- data.frame( 
  state = c( "AR" ) , 
  ac = c( 0.43 ) , 
  man = c( 0.26 ) , 
  ltc = c( 0.25 ) , 
  care = c( 0.05 ) , 
  dsh = c( 0.01 ) 
)

y2 <- melt( y , id.var="state" )

threshold <- .07

y2 <- y2 %>%
  mutate(cs = rev(cumsum(rev(value))),
         ypos = value/2 + lead(cs, 1),
         ypos = ifelse(is.na(ypos), value/2, ypos),
         xpos = ifelse(value > threshold, 1, 1.3),
         xn = ifelse(value > threshold, 0, .5))

test <- ggplot( y2 , aes( x=1 , y=value , fill=variable )) +
  geom_bar( width = 1 , stat = "identity" ) +
  geom_text_repel( aes( label = paste( y2$variable , percent( value )), x = xpos, y = ypos ) , 
                   color="white" , size=5, nudge_x = y2$xn, segment.size = .5 ) +
  coord_polar( "y" , start = 0 ) + 
  scale_fill_manual( values=c( "#003C64" , "#0077C8" , "#7FBBE3" , "#BFDDF1" , "#00BC87" ) ) +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid  = element_blank())

test