Reputation: 571
I have a dataframe (df) that shows emotions associated with various categories of business:
My task is to create pie charts showing the % of emotions for each type of business. So I need to create a function in matplotlib that reads the "Business" column and then builds a pie chart using each of the emotion categories for each row in the dataframe.
I've already built a bar plot, but I am having no luck with the pie chart. EDIT: HERE IS MY CODE FOR THE BAR PLOT:
import pandas as pd
import csv
import matplotlib.pyplot as plt
GraphData = open("barGraph.csv")
df = pd.read_csv('barGraph.csv')
ax = df.plot(kind='bar', title ="Emotions at Various Businesses", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Business Type",fontsize=12)
ax.set_ylabel("Strength of Emotion",fontsize=12)
ax.set_xticklabels(['Beauty & Spas', 'Burgers-Restaurants', 'Pizza', 'Mexican Restaurants', 'Modern European-Restaurants', 'Chinese'])
plt.show()
I've read the documentation on pie charts, but it isn't making sense to me, at least as it pertains to drawing the data from a dataframe as opposed to a series.
Any suggestions?
Upvotes: 3
Views: 12629
Reputation: 294218
Consider the dataframe df
df = pd.DataFrame(dict(
Business='Beauty & Spas;Burgers-Restaurants;Pizza;Mexican Restaurants;Modern European-Restaurants;Chineese'.split(';'),
aniticipation=[0] * 6,
enjoyment=[6., 1., 6., 33.,150., 19.5],
sad=[1., 2., 1., 3., 13.5, 0.],
disgust=[1, 1, 0, 3, 37, 3],
anger=[1.5, 2., 4., 9., 19., 3.],
surprise=[3, 0, 0, 2, 12, 1],
fear=[0, 1, 1, 9, 22, 1],
trust=[0] * 6
))
You can create pie charts like this
fig, axes = plt.subplots(2, 3, figsize=(10, 6))
for i, (idx, row) in enumerate(df.set_index('Business').iterrows()):
ax = axes[i // 3, i % 3]
row = row[row.gt(row.sum() * .01)]
ax.pie(row, labels=row.index, startangle=30)
ax.set_title(idx)
fig.subplots_adjust(wspace=.2)
Upvotes: 11