首页 > 解决方案 > 在 ggplot2 饼图中移动标签

问题描述

我知道如何避免饼图中的标签重叠,我可以用它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% 将位于灰色区域。

标签: rggplot2pie-chart

解决方案


这绝不是优雅的,但它可能会提供您正在寻找的东西。这种方法涉及计算标签的位置(for 中的中点valuey,并使用不同的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

使用 geom_text_repel 具有不同标签位置的 ggplot


推荐阅读