ggplot pie chart labeling

前端 未结 2 1538
余生分开走
余生分开走 2020-12-18 01:52

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:

相关标签:
2条回答
  • 2020-12-18 02:01

    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))
    

    0 讨论(0)
  • 2020-12-18 02:17

    We can make it work with ggplot2 and the ggrepel package.

    Unfortunately geom_text_repel() does not support a position = argument, so we have to calculate the starting position of the line by hand.

    With your data.frame:

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

    This calculates the mean point for each group (or obs, or whtvr you want to call it).

    Plugging it in in the geom_text_repel's y aes gives a nice result:

    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()
    

    I made some choices, as the use of text instead of label, the removal of the legend and the axes. Feel free to change them

    0 讨论(0)
提交回复
热议问题