Reputation: 421
I'm running the groupby utility function on my dataframe object and I want to generate a bar chart after this. I'm expecting two bars next to each i.e one for each week:
Here is the code:
df3 = (
self.df
.groupby(by=['week', 'type'], dropna=False)
.sum()
.unstack()
)
which produces that:
type type1 type2
week
1 81.44 NaN
2 591.30 1900.0
3 91.10 NaN
4 146.48 11000.0
5 218.76 NaN
I'm kinda struggling now to plot it by calling:
axs.bar(numpy.arange(5, 1), df3)
which outputs "ValueError: shape mismatch: objects cannot be broadcast to a single shape".
Any help will be appreciated!
Upvotes: 1
Views: 356
Reputation: 659
You need to provide the .bar() method also with the height of the single columns (i.e. your dataframe columns).
import pandas as pd, numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame([
[1, 'type1', 81.44],
[2, 'type1', 591.3],
[2, 'type2', 1900],
[3, 'type1', 91.1],
[4, 'type1',146.48],
[4, 'type2', 11000],
[5, 'type1', 218.76]
], columns=['week', 'type', 'value'])
df3 = df.groupby(by=['week', 'type'])\
.sum()\
.unstack()
# Create plot
# Define the variables to display
bars = [df3.value.type1, df3.value.type2]
# Create the axes
axs = plt.subplot(111)
# Plot 'type1'
axs.bar(x = np.arange(1, 1 + len(bars[0])) - .15, height = bars[0], width = .2, data = df3)
# Plot 'type2'
axs.bar(x = np.arange(1,1 + len(bars[1])) + .15, height = bars[1], width = .2, data = df3)
Upvotes: 1
Reputation: 150735
How about passing the option ax
to df3.plot
?
df3.plot.bar(ax=axs)
Upvotes: 0