在ggplot2饼图中移动标签

时间:2019-09-25 15:55:20

标签: r ggplot2 pie-chart

我从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

enter image description here

因此在此示例中,1%和5%将在灰色区域。

1 个答案:

答案 0 :(得分:1)

这绝不是优雅,但它可以提供您想要的东西。此方法涉及计算标签的位置(O3的{​​{1}}的中点),并对带有分段的外部标签使用不同的value位置和y。也许这会给你一些想法吗?

x

ggplot with varied label locations using geom_text_repel