R 在ggplot2饼图中移动标签

R 在ggplot2饼图中移动标签,r,ggplot2,pie-chart,R,Ggplot2,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

我知道我可以使用
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
库(ggrepel)
图书馆(GG2)
图书馆(dplyr)
图书馆(比例尺)
图书馆(重塑)

这一点也不优雅,但它可以提供您所需要的。该方法包括计算标签的位置(对于
y
,在
值中的中点),并使用不同的
x
位置和
轻推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
库(ggrepel)
图书馆(GG2)
图书馆(dplyr)
图书馆(比例尺)
图书馆(重塑)
Y