Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • line connectors in pie plot for too small slices

    Dear Stata uses,

    I seldom use pie plot, people often point out its flaws. But I have to use it for a report, layman seems to like pie chart (maybe human do like circle). If you use the following codes to graph a pie plot, you will find that in some slices there are overlap of plabels. In this data example, slices represent manager, profession, technician and selfemp categories are too small to label. I wonder is there some way to put the plabels outside the slice or apart from each other, and use some line connectors to connecte the corresponding slices. Thank you.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(ratio1 ratio2 ratio3 ratio4 ratio5 ratio6 ratio7 ratio8)
    .2991214 .011514423 .020533217 .2432774 .021481434 .2438631 .010377994 .09076492
    end
    Code:
    local la "farmer manager profession student technician worker selfemp others"
    forvalues n = 1/8 {
     local nla: word `n' of `la'
     label var ratio`n' "`nla'"
     }
     
    graph pie ratio*, sort descending legend(posi(6) row(4)) plabel(_all percent, format(%2.1f)) plotregion(style(none))

  • #2
    Pies make sense when they show proportions of a total. They often work poorly then, but they make sense. Your "ratio" doesn't sum to 1, so pie charts are ruled out on that basis. I won't even try to improve your pie code, just suggest that you insist on something different.

    Code:
    clear
    input float(ratio1 ratio2 ratio3 ratio4 ratio5 ratio6 ratio7 ratio8)
    .2991214 .011514423 .020533217 .2432774 .021481434 .2438631 .010377994 .09076492
    end
    
    gen id = 1 
    reshape long ratio, i(id) j(which) 
    tokenize "farmer manager profession student technician worker selfemp others"
    
    su ratio 
    di r(sum) 
    
    forval i = 1/8 { 
        label def which `i' "``i''" , modify 
    } 
    label val which which 
    
    graph hbar (asis) ratio, over(which, sort(1) descending) bar(1, bfcolor(blue*0.2) blcolor(blue)) ytitle(ratio) ysc(alt)
    Click image for larger version

Name:	notapie.png
Views:	1
Size:	28.6 KB
ID:	1469845

    Comment


    • #3
      Thank you Nick, I learn more through reading your codes. Please allow me to cite some remarks in Quick-R site, although it's a bit inappropriate to cite R in a Stata forum:
      Pie charts are not recommended in the R documentation, and their features are somewhat limited. The authors recommend bar or dot plots over pie charts because people are able to judge length more accurately than volume.
      As to the pie chart, there's still some audience, readers and sponsors in need of it, but in a more beautiful form, more stereoscopic, more colorful and no overlaping plables. However -tabplot- be a more scientific demonstration tool, non-professional people read traditional bar plot more easily.
      https://stackoverflow.com/questions/...-charts-with-r
      Click image for larger version

Name:	pieplot.png
Views:	1
Size:	541.9 KB
ID:	1469853

      Comment


      • #4
        Nick Cox wrote a command -pieplot- in 2009 (from SSC). -pieplot- plots pie charts of categorical frequencies. As it described in help file, this command is a convenience command providing an alternative to graph pie, over() for pie charts showing categorical frequencies. (Only a memo.)

        Comment


        • #5
          Hope that graph pie can create 'rectangles' easily.
          https://www.statalist.org/forums/forum/general-stata-discussion/general/1483934-help-with-spmap-legend-option
          https://www.statalist.org/forums/for...horopleth-maps
          Last edited by Chen Samulsion; 11 Mar 2019, 08:29.

          Comment


          • #6
            I guess you can do some of that in the Graph Editor.

            Otherwise I can't whip up any enthusiasm for this, even for someone else taking time to automate this.

            Making a lousy graph slightly less lousy is not a good use of anyone's time when a better one is easy. Naturally, that's just one opinion.

            Comment


            • #7
              OK, Nick, I can remove pie chart from my toolkit, using bar chart, box plot or dot plots as substitutes for it.

              Comment


              • #8
                Dear Choonjoo Lee, I dug this thread up, and you must have workaround.

                Comment


                • #9
                  Dear Chen Samulsion , yes—there is a workaround using official Stata graphics.
                  Click image for larger version

Name:	pie_connectors_careful.png
Views:	1
Size:	261.6 KB
ID:	1788122



                  We can draw the sectors with twoway area, place the labels outside the circle, and use pcspike for the connectors. The label positions are calculated from the data, with a minimum vertical separation on each side.
                  Before doing that, I would retain Nick’s point about the denominator. The eight supplied values sum to 0.940933888, not 1. The example below therefore explicitly displays composition within the eight supplied categories, using their sum as the denominator. It does not add an assumed residual category or modify “others.”
                  This interpretation requires the categories to be nonoverlapping components measured on a common basis. If that is not appropriate, normalization does not make a pie chart appropriate. I have also included a horizontal bar chart that preserves the original values without renormalization.
                  The complete example below requires no additional packages and was tested in Stata/MP 16.1. Please run the whole block together from the Do-file Editor.
                  Code:
                  version 16
                  set more off
                  preserve
                  clear
                  
                  * Original values from the question
                  input str12 category double value
                  farmer     .2991214
                  manager    .011514423
                  profession .020533217
                  student    .2432774
                  technician .021481434
                  worker     .2438631
                  selfemp    .010377994
                  others     .09076492
                  end
                  
                  isid category
                  assert value>0 & !missing(value)
                  
                  quietly summarize value, meanonly
                  local total=r(sum)
                  display "Sum of supplied values = " %12.9f `total'
                  
                  * Explicit denominator: the sum of the supplied categories
                  generate double share=value/`total'
                  
                  * 1. Companion graph: original values, without renormalization
                  graph hbar (asis) value, over(category, sort(1) descending) ///
                      blabel(bar, format(%6.4f) size(small)) ///
                      bar(1, color(navy*.65)) yscale(range(0 .36)) ///
                      ylabel(0(.1).3) ytitle("Original supplied value") ///
                      title("Original values: no renormalization",size(medsmall)) ///
                      note("The supplied values sum to `=string(`total',"%9.7f")', not 1." ///
                           "This display retains the values as posted; it does not assume a complete composition.", ///
                           size(vsmall)) ///
                      graphregion(color(white)) name(original_values,replace)
                  
                  * 2. Sector positions, starting at the top and proceeding clockwise
                  gsort -share category
                  generate int slice=_n
                  generate double finish=sum(share)
                  generate double start=finish-share
                  assert abs(finish[_N]-1)<1e-12
                  
                  generate double middle=2*_pi*(start+share/2)
                  generate double ax=1.01*sin(middle)
                  generate double ay=1.01*cos(middle)
                  generate byte side=cond(ax>=0,1,-1)
                  generate double ly=1.12*cos(middle)
                  
                  * 3. Separate labels vertically while retaining their order
                  sort side ly
                  by side: replace ly=max(ly,ly[_n-1]+.19) if _n>1
                  by side: egen double ymax=max(ly)
                  replace ly=ly-max(0,ymax-1.14)
                  
                  by side: assert ly-ly[_n-1]>=.19-1e-10 if _n>1
                  assert inrange(ly,-1.2,1.2)
                  
                  generate double ex=side*1.20
                  generate double tx=side*1.42
                  generate str40 caption=category+"  "+ ///
                      strtrim(string(100*share,"%4.1f"))+"%"
                  
                  sort slice
                  list category value share, noobs
                  
                  * 4. Each sector is a closed polygon: center, arc, center
                  local n=_N
                  expand 183
                  bysort slice: generate int vertex=_n
                  generate double theta=2*_pi*(start+share*(vertex-2)/180)
                  generate double px=sin(theta)
                  generate double py=cos(theta)
                  replace px=0 if inlist(vertex,1,183)
                  replace py=0 if inlist(vertex,1,183)
                  
                  * Keep one connector and label per sector
                  foreach v in ax ay ex tx ly {
                      replace `v'=. if vertex!=1
                  }
                  replace caption="" if vertex!=1
                  
                  local colors "navy teal cranberry orange forest_green lavender gold sand"
                  local plots
                  forvalues i=1/`n' {
                      local col : word `i' of `colors'
                      local plots `plots' ///
                          (area py px if slice==`i', nodropbase ///
                          fcolor(`col') fintensity(80) lcolor(white) lwidth(thin))
                  }
                  
                  * 5. Draw sectors, connectors and outside labels
                  twoway `plots' ///
                      (pcspike ay ax ly ex, lcolor(gs5) lwidth(thin)) ///
                      (pcspike ly ex ly tx, lcolor(gs5) lwidth(thin)) ///
                      (scatter ly tx if side==1, msymbol(none) mlabel(caption) ///
                          mlabposition(3) mlabgap(1) mlabsize(small) mlabcolor(black)) ///
                      (scatter ly tx if side==-1, msymbol(none) mlabel(caption) ///
                          mlabposition(9) mlabgap(1) mlabsize(small) mlabcolor(black)), ///
                      xscale(range(-2.5 2.5) off) ///
                      yscale(range(-1.3 1.3) off) ///
                      xlabel(none) ylabel(none) legend(off) aspectratio(.52) ///
                      title("Composition within the eight supplied categories", ///
                          size(medsmall)) ///
                      subtitle("Percent of the supplied total; outside labels with connectors", ///
                          size(small)) ///
                      note("Percentages are normalized over the eight supplied values (sum = `=string(`total',"%6.4f")')." ///
                           "These are not percentages of an independently established population total. No residual category was added.", ///
                           size(vsmall)) ///
                      graphregion(color(white)) ///
                      plotregion(color(white) margin(zero)) ///
                      xsize(11) ysize(7) name(pie_connectors,replace)
                  
                  restore
                  For example, “farmer” is labeled 31.8% because 0.2991214 is divided by the supplied total, 0.940933888. That is a different quantity from interpreting the original value as 29.9% of some larger population.
                  The example automatically separates the small-slice labels without assigning individual label coordinates manually. The spacing, palette, and plotting dimensions are chosen for these eight categories; substantially more categories or longer labels would require adjustments.
                  This addresses the connector-and-label question while keeping the interpretation of the pie explicit. The bar chart remains available as a simpler display of the original magnitudes.

                  One limitation of this example is that the label spacing is tuned to these eight categories; it does not measure the actual text dimensions. A more general implementation would need to account for font size, label length, available space, and connector crossings, with alternatives such as wrapping labels or using a legend when space is insufficient. The current code is therefore a working example rather than a general-purpose collision-avoidance routine.
                  Last edited by Choonjoo Lee; 14 Nov 2026, 09:21.

                  Comment


                  • #10
                    Dear Choonjoo Lee, thank you for your devotion to this. If this is in fact so complicated to implement in Stata, then I don't think there's really any need to force Stata to do something it wasn't designed for. I should just switch to Excel—although I basically haven't used pie charts for five or six years now.

                    Comment


                    • #11
                      Thank you, Chen Samulsion . I should clarify that this is feasible in Stata—the example already produces the outside labels and connectors. The complexity I mentioned concerns making the label placement work reliably across different datasets, label lengths, font sizes, and graph dimensions.

                      A reusable command would be possible, but we would first need to define its scope and how it should handle crowded labels. I do not know why this is not a built-in option; development priorities may be part of the explanation, but that would be speculation on my part.

                      For an occasional chart, using whichever tool is most convenient is entirely reasonable. I simply wanted to distinguish the additional work needed for a general-purpose implementation from a technical limitation of Stata itself.

                      Comment


                      • #12
                        Many thanks, Lee. An interesting material here https://plotly.com/blog/pie-chart-guide/
                        The earliest known pie charts are in William Playfair's Statistical Breviary of 1801, including one of the Turkish Empire's territory in Asia, Europe and Africa (Wikipedia; Ian Spence traces their origins in "No Humble Pie", 2005). In 1858 Charles Joseph Minard placed pie charts on a map of the cattle sent to Paris from across France, the idea behind today's bubble pie charts, and Florence Nightingale sent Queen Victoria her polar area diagram of army deaths in the Crimea, a pie whose wedges vary in length instead of angle (our wind rose guide redraws it with Plotly). Statisticians have long preferred bars, because Cleveland and McGill found that people judge angles less accurately than lengths (1984), but for reading proportions of a whole Spence and Lewandowsky found "little to choose between the pie and the bar chart" (1991).

                        Comment


                        • #13
                          Florence Nightingale's graph isn't a pie chart at all. It doesn't show sectors or slices. It shows frequencies varying with month of year as superimposed line graphs, so the only similarity with pie charts is the use of a polar or radial design, more like those often used now (indeed, over-used) as radar or spider charts (as usual, there are other names).

                          Nightingale is the subject of many memes or myths. One is that she invented the graph she used, whereas she prominently acknowledged that she took the idea from WIlliam Farr, and a little rummaging shows several people who were there earlier.

                          It's not even clear that it is a good graph for the data she showed, for deaths of soldiers in the Crimean War from various causes. Deaths weren't strongly seasonal. Sure, winter was not good for soldiers being or becoming sick or injured (or dead), but neither were battles. Over the course of the war, deaths fluctuated for various reasons, good reasons being some improvements in treatment and above all the cessation of hostilities. As her data covered more than a year, she needed to use two charts side by side.

                          I have seen some puzzling interpretations of why Nightingale's graph become noticed, some with the flavour that she needed to use an offbeat design to attract attention, which if true is to me dismaying.

                          Nightingale's history and later reputation have been vigorously and even viciously debated. Nightingale scholars and other writers, some but not all with serious background, seem to get into some very tense disagreements with each other. The main positives that appear to remain is that she did serve valiantly as a nurse and that her publicity and analysis of the medical and other problems in nursing was very thorough and had to be taken seriously.

                          Pie charts have a long history. Oddly pie chart as the dominant term didn't emerge as a standard until the early 20th century. Other critiques of pie charts that should be mentioned include those of Edward Tufte in The Visual Display of Quantitative Information (1983, slightly revised second edition 2001) and Willard C. Brinton in Graphic Methods for Presenting Facts (1914). I was able to find a second-hand (used) copy of Brinton for a modest price several years ago. The paper remains in excellent condition but the binding split and even disintegrated, and I spent more getting the book rebound than on the original. Now good used copies if you can find one would probably cost much more than I paid, hundreds of GBP or USD. There are some nasty and not always very cheap reprints available -- but the whole work can be found as a pdf too.

                          I am just guessing, but I doubt that StataCorp will (or -- personal opinion -- should) devote time and effort to enhancing graph pie.

                          Comment


                          • #14
                            Hi Chen Samulsion ,
                            Following our discussion, I have put together a Stata command, radialchart, that can place labels outside small pie slices and connect them to the corresponding slices. It also supports donut charts.
                            Click image for larger version

Name:	chen_colored.png
Views:	1
Size:	115.9 KB
ID:	1788134

                            Click image for larger version

Name:	chen_donut.png
Views:	1
Size:	104.0 KB
ID:	1788135

                            Click image for larger version

Name:	browser_preview.png
Views:	1
Size:	45.2 KB
ID:	1788136

                            Click image for larger version

Name:	help_02.png
Views:	1
Size:	41.1 KB
ID:	1788137

                            Click image for larger version

Name:	help_03.png
Views:	1
Size:	37.5 KB
ID:	1788138



                            The code is available here: https://github.com/renegade68/piechart
                            You can install it directly in Stata:
                            Code:
                            net install radialchart, from("https://raw.githubusercontent.com/renegade68/piechart/main") replace
                            help radialchart
                            Here is a self-contained example:
                            Code:
                            preserve
                            clear
                            input str24 category double value
                            "Main activity" 90
                            "Secondary activity" 7
                            "Small category A" 2
                            "Small category B" 1
                            end
                            radialchart value, over(category) labels(mixed) outsidepct(5) ///
                            insidecontent(percent) connectcolor(slice) anchors
                            
                            restore
                            Here, slices representing 5% or less receive outside labels with connectors. Larger slices display their percentages inside. You can use labels(outside) to place all labels outside, or add hole(.5) for a donut.
                            For more demanding label layouts, the companion command radialchart_export produces an HTML file that measures text in the browser, supports automatic wrapping, and checks for overlaps before allowing SVG download. See help radialchart_export for a complete example.
                            I have tested the commands on macOS, including installation from GitHub and the help-file examples. Windows testing is still pending. If you have an opportunity to try them with your data, I would welcome your feedback—particularly on label placement and the appearance of the connectors.

                            Musau’s tip provides a useful way to create donut charts using graph pie and Graph Editor commands. Our implementation takes a different approach: it draws the ring sectors directly and adds reusable options for outside labels, connector lines, hole size, and center text. The main extension is therefore the geometry and label-handling functionality, rather than the donut chart itself.

                            Best regards,
                            Last edited by Choonjoo Lee; 15 Nov 2026, 10:02.

                            Comment


                            • #15
                              See also

                              Code:
                              SJ-21-4 gr0089  . . . . . . . .  Stata tip 143: Creating donut charts in Stata
                                      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A. Musau
                                      Q4/21   SJ 21(4):1069--1073                              (no commands)
                                      tip on creating donut charts

                              Comment

                              Working...
                              X