【问题标题】:ggplot pie chart labelingggplot饼图标注
【发布时间】:2017-06-09 14:54:20
【问题描述】:

我正在努力使饼图标签正确。环顾四周,认为我可以轻松实现mathematicalCoffee 所做的事情。到目前为止,我有这个代码:

ltr = LETTERS[seq( from = 1, to = 26)]

wght = runif(length(ltr))
wght = wght/sum(wght)
wght = round(wght, digits = 2)

alloc = as.data.frame(cbind(ltr, wght))
alloc$wght = as.numeric(as.character(alloc$wght))

ggpie <- function (dat, by, totals) {
  ggplot(dat, aes_string(x=factor(1), y=totals, fill=by)) +
    geom_bar(stat='identity', color='black') +
    guides(fill=guide_legend(override.aes=list(colour=NA))) +
    coord_polar(theta='y') +
    theme(axis.ticks=element_blank(),
          axis.text.y=element_blank(),
          axis.text.x=element_text(colour='black'),
          axis.title=element_blank()) +
    ## scale_fill_brewer(palette = "GnBu") +
    scale_y_continuous(breaks=cumsum(dat[[totals]]) - dat[[totals]] / 2, labels=paste(dat[[by]], ":", dat[[totals]]))    
}

AA = ggpie(alloc, by = "ltr", totals = "wght") +
  ggtitle("Letter weights")

AA

生成的饼图:

有没有办法生成这样的东西,例如:

建议的 dup 更新 - 我认为该线程更多地是关于饼图的替代品以及为什么饼图不好。我想坚持使用饼图,并希望找到一种解决方案来正确/用户友好地处理标签。

【问题讨论】:

标签: r ggplot2 pie-chart


【解决方案1】:

对于饼图,plotly 比 ggplot 容易得多。也许是这样的:

library(plotly)

p <- plot_ly(alloc, labels = ~ltr, values = ~wght, type = 'pie',textposition = 'outside',textinfo = 'label+percent') %>%
  layout(title = 'Letters',
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

【讨论】:

  • 感谢您的回复。您能否展示使用plotly 生成的任何饼图,并提供用户友好的标签?
  • 查看此参考中的样式饼图示例:plot.ly/r/pie-charts 在这里您可以设置标签/颜色以及定义标签位置。
  • 嗯,它部分地完成了我所追求的。假设馅饼的碎片非常小,并且多个标签应该位于切片区域之外。就像我上面提供的示例一样。 plotly 擅长这个吗?
  • 嗯不太确定,我相信标签在重叠时会被躲避,因此在超薄标签的情况下应该覆盖这一点。 plotly 中有注释选项可以为您提供第二个示例中显示的线条,但恐怕这会花费大量自定义工作。
  • 哈,我尝试将 ltr 替换为 ltr = 1:150 来试一试,重新运行脚本会给你一个非常棒的馅饼,但不确定它是否可读
【解决方案2】:

我们可以使它与ggplot2ggrepel 包一起使用。

很遗憾geom_text_repel() 不支持position = 参数,所以我们必须手动计算行的起始位置。

与您的data.frame

alloc$pos = (cumsum(c(0, alloc$wght)) + c(alloc$wght / 2, .01))[1:nrow(alloc)]

这会计算每个组(或 obs,或您想要调用它的 whtvr)的平均点。

将其插入geom_text_repely aes 会产生不错的结果:

library(ggplot2)
library(ggrepel)
ggplot(alloc, aes(1, wght, fill = ltr)) +
    geom_col(color = 'black', 
             position = position_stack(reverse = TRUE), 
             show.legend = FALSE) +
    geom_text_repel(aes(x = 1.4, y = pos, label = ltr), 
                    nudge_x = .3, 
                    segment.size = .7, 
                    show.legend = FALSE) +
    coord_polar('y') +
    theme_void()

我做了一些选择,使用text 代替label,去掉了图例和坐标轴。随意更改它们

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多