Tag Archive


amateur astronomy awk bash be b[e] supergiant cartoon conference convert exoplanet fedora figaro fits fun galaxy history iraf jupiter latex linux lmc massive star matplotlib meteor mypaper ondrejov observatory optical paper peblo photometry planet pro-am pyraf python scisoft skinakas observatory small magellanic cloud smc spectroscopy starlink talk theli ubuntu university of crete video x-ray

matplotlib’s pie colors or why pie diagrams suck!

While asking around for the best solution in how to determine the colors inside the matplotlib’s pie function I found out that the best solution is just … not to use them at all! (At least if they are not more than a couple of objects!)

Well, the problem starts from the fact that when pie assigns the colors automatically then black (one of the predefined colors) covers the text (black also) and the percentage of the specific part cannot be seen. So the question is how to remove this? One answer (thanks to Tony Y.) included to set the rcParams by typing:

>>> import matplotlib.pyplot as plt
>>> plt.rcParams['axes.color_cycle'].remove('k')

but for some reason**, although the black was removed from the list, the pie kept using the black! Moreover the color_cycle is limited to 8 colors ([‘b’, ‘g’, ‘r’, ‘c’, ‘m’, ‘y’, ‘k’]) so after the 8th part the colors start repeating again, so actually no point… Another solution is to give specifically the colors (like colors=(‘g’,’r’,’b’,’y’,’c’,’m’,’#e23f5f’,’#eeefff’, ‘#ffee88’) inside the pie) but this works if you know the number of pie parts, unless you create a more dynamic way to generate colors.

But this is probably getting too much (if not useless and boring…) and moreover if there are many objects then the pie diagram does not help to understand what it represents. Che M. pointed out a very interesting page which explains really easily why pie diagrams should just be … forgotten totally and replaced by bar plots which are by far a better way to present (and comment easily) data.

So finally I decided to follow this path… ignore pie and go on with the bar plots!

>>> added at 6 Dec 2011 >>>
** It is not removed because it is actually hard-coded in the function (pointed out by Tony Y.).

Another approach would be to change the way that the text appears and this is successful by using this code (by Jae-Joon L.):
a = pie([1,2,4,3], labels=["1", "2", "4", "3"], autopct="%d")
from matplotlib.patheffects import withStroke
effect_whiteborder = withStroke(foreground="w", linewidth=3)
for txt in a[2]:
    txt.set_path_effects([effect_whiteborder])

which works and the text is obvious over black color.