How to plot a dictionary of dataframes to subplots

Viewed 705

I have a dict including different series. Each series has a different length and I am going to have plots of bar chart for them, each in a subplot. Here is the dict:

data = {'df_A': 0         0
 1         0
 2         0
 3         0
 4         0
 5     14343
 6     14343
 7         0
 8      8107
 9        11
 10        0
 11     2276
 12        0
 dtype: int64,
 'df_B': 0       0
 1       0
 2       0
 3    6692
 dtype: int64,
 'df_C': 0    323059
 1         0
 2         0
 3         0
 dtype: int64}

To have the plot, I run the following code, but I get the error: 'numpy.ndarray' object has no attribute 'bar'

import matplotlib.pyplot as plt
  
fig, ax = plt.subplots(nrows = 3, ncols = 1)

for i,key in enumerate(data):

     ax.bar(range(len(data[key])),list(data[key]))
2 Answers

Building on the observation of @BigBen, and using Dataframe.plot.bar:

import pandas as pd
import matplotlib.pyplot as plt

data = {'df_A': pd.DataFrame([0, 0, 0, 0, 0, 14343, 14343, 0, 8107, 11, 0, 2276,0]),
        'df_B': pd.DataFrame([0, 0, 0, 6692]),
        'df_C': pd.DataFrame([323059, 0, 0, 0])}

fig, axes = plt.subplots(nrows = 3, ncols = 1)

for i, key in enumerate(data):

     data[key].plot.bar(ax=axes[i]) # Tell the DataFrame which axis to add the plot to

plt.show()
  • See How to loop over the axes in a subplot to loop through, and plot to an axes.
  • The OP shows a dictionary of DataFrames
  • Use pandas.concat to combine the dataframes in the dictionary into a single dataframe, and then plot with pandas.DataFrame.plot
    • I recommend setting sharey=True (False by default), to show all the bars on the same scale.
  • This is a simpler implementation, which removes the need to iterate through a dictionary, and axes.
import pandas as pd
import matplotlib.pyplot as plt

data = {'df_A': pd.DataFrame([0, 0, 0, 0, 0, 14343, 14343, 0, 8107, 11, 0, 2276,0]),
        'df_B': pd.DataFrame([0, 0, 0, 6692]),
        'df_C': pd.DataFrame([323059, 0, 0, 0])}

# combine the dataframes
df = pd.concat(data.values(), axis=1)

# set the column names
df.columns = data.keys()

# plot the dataframe
df.plot(kind='bar', subplots=True, figsize=(6, 6), legend=False)

# rotate the ticks
plt.xticks(rotation=0)

# add separation between the figures
plt.tight_layout()

plt.show()

enter image description here

Related