Skip to content

Instantly share code, notes, and snippets.

@brinnaebent
Last active November 16, 2020 22:55
Show Gist options
  • Save brinnaebent/bff18d3540e2723e54b3816e6509ea79 to your computer and use it in GitHub Desktop.
Save brinnaebent/bff18d3540e2723e54b3816e6509ea79 to your computer and use it in GitHub Desktop.
import pandas as pd
import numpy as np
# Read the data
df = pd.read_csv('thanksgiving-2015-poll-data.csv')
# List the pie types (you can see these by reading the Readme or viewing the columns of df using the command df.columns)
pielist = ['Apple', 'Buttermilk', 'Cherry', 'Chocolate', 'Coconut cream', 'Key lime', 'Peach', 'Pecan', 'Pumpkin', 'Sweet Potato']
# Make a dictionary and fill it with the count of each column/pie
piedict = dict()
for p in pielist:
item_counts = df[('Which type of pie is typically served at your Thanksgiving dinner? Please select all that apply. - ' + p)].value_counts()
piedict[p] = item_counts[0]
# Transform the dictionary into a dataframe
piedf = pd.DataFrame.from_dict(piedict, columns = ['Count'], orient='index')
# Create a percent column
piedf['Percent'] = (piedf['Count']/sum(piedf['Count']))*100
# Make the keys and percent into lists
Keys = piedf.index.to_list()
Percent = piedf['Percent'].to_list()
# For the pie chart, the labels will be equal to Keys and the sizes of the wedges will be equal to Percent
labels = Keys
sizes = Percent
# Create a figure and set layout, font size, font family, and figure size
fig, ax = plt.subplots(figsize=(15,15))
plt.rcParams.update({'font.size': 40, 'font.family': 'Gabriola'})
plt.tight_layout()
# This is the pie plot
fig.subplots_adjust(-.07,-.08,1.08,1.13) # This is where you want to adjust if you use a different image and it doesn't line up properly
ax.set_aspect("equal")
slices, labels = ax.pie(sizes, labels=labels, wedgeprops = {'fc':'none', 'ec':'white', 'lw':5})
# This is your pie image
img = plt.imread("pie-bck.png")
ax2 = fig.add_axes([0,0,1,1], zorder=-1) #zorder is -1 because it is layered behind the pie chart
ax2.axis("off")
ax2.imshow(img)
# When saving the figure, you will want to use the bbox_inches = "tight" argument. Otherwise, it may cut off your labels
plt.savefig('piechart.png', transparent=True, bbox_inches = "tight")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment