ggplot饼图标签 [英] ggplot pie chart labeling
问题描述
我正在努力使饼图标签正确无误.环顾四周,以为我可以轻松实现 mathematicalCoffee 做到了.到目前为止,我有以下代码:
I am struggling with getting the pie chart labels correct. Looked around and thought that I could easily implement what mathematicalCoffee did. So far I have this code:
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
结果饼图:
有什么方法可以生成这样的东西,例如:
Is there any way to generate something like this, for example:
建议的重复项更新-我认为该主题更多地是关于饼图的替代品,以及为什么饼图不好.我想坚持使用饼图,并想找到一种正确/方便用户使用标签的解决方案.
Update for suggested dup - I think that thread is more about alternatives to pie charts and why pie charts are bad. I would like to stick to pie charts and want to find a solution to handling labels correctly/user-friendly.
推荐答案
对于饼图,plot比ggplot容易得多.也许是这样的:
For pie charts plotly works a lot easier than ggplot. Perhaps something like this:
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))
这篇关于ggplot饼图标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!