I am trying to make pie charts where some of the wedges have hatching and some of them don’t, based on their content. The data consists of questions and yes/no/in progress answers, as shown below in the MWE.
import pandas as pd import matplotlib.pyplot as plt raw_data = {'Q1': ['IP', 'IP', 'Y/IP', 'Y', 'IP'], 'Q2': ['Y', 'Y', 'Y', 'Y', 'N/IP'], 'Q3': ['N/A', 'IP', 'Y/IP', 'N', 'N']} df = pd.DataFrame(raw_data, columns = ['Q1', 'Q2', 'Q3']) df= df.astype('string') colors={'Y':'green', 'Y/IP':'greenyellow', 'IP':'orange', 'N/IP':'gold', 'N':'red', 'N/A':'grey' } for i in df.columns: pie = df[i].value_counts().plot.pie(colors=[colors[v] for v in df[i].value_counts().keys()]) fig = pie.get_figure() fig.savefig("D:/windows/"+i+"test.png") fig.clf()
However, instead of greenyellow
and gold
I am trying to make the wedges green with yellow hatching, and yellow with red hatching, like so (note the below image does not match the data from the MWE):
I had a look online and am aware I will likely have to split the pie(s) into individual wedges but can’t seem to get that to work alongside the pandas value counts. Any help would be massively appreciated. Thanks!
Advertisement
Answer
This snippet shows how to add hatching in custom colors to a pie chart. You can extract the Pandas valuecount – this will be a Series – then use it with the snippet I have provided.
I have added the hatch color parameter as a second parameter in the color dictionary:
import matplotlib.pyplot as plt colors={'Y' :['green', 'lime'], 'IP': ['orange', 'red'], 'N' : ['red', 'cyan']} labels=['Y', 'N', 'IP'] wedges, _ = plt.pie(x=[1, 2, 3], labels=labels) for pie_wedge in wedges: pie_wedge.set_edgecolor(colors[pie_wedge.get_label()][1]) pie_wedge.set_facecolor(colors[pie_wedge.get_label()][0]) pie_wedge.set_hatch('/') plt.legend(wedges, labels, loc="best") plt.show()