r - 在 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% 将位于灰色区域。
解决方案
这绝不是优雅的,但它可能会提供您正在寻找的东西。这种方法涉及计算标签的位置(for 中的中点value
)y
,并使用不同的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
推荐阅读
- bokeh - 修补完整数据列的最佳做法是什么?
- robotframework - 如何使用机器人框架选择 ifream。(其中 Xpath、ID 和名称不可用)
- c - 如何通过函数为 typedef 别名指针赋值?
- javascript - 如何将锚文本分配为变量并通过 gtag 事件将其传递给 Google Analytics
- python - 保存并从磁盘重新加载后获取 Keras 模型的(输入)层
- ios - 为什么 swift 在这里使用结构作为字典键而不是字符串?
- .net - 如何在不影响分段分隔符的情况下对 URI 进行编码?
- apama - Apama HTTPClient 适配器中的 JSON 响应解析
- java - 调用 android.widget.ListView.setAdapter(android.widget.ListAdapter) 时出错
- powershell - 如何使用 Gmail 作为 SMTP 服务器发送邮件