user8270077
user8270077

Reputation: 5071

Plotting multiple plots in a grid with pandas and pyplot

I have a list with pandas dataframes each comprising a timeseries.

When I try to plot them in a grid I get them all appearing in the same plot instead (i.e. not in a grid each one occupying a cell of the grid). My code is here:

for i in range(len(building_ids)): # building_ids is the list containing the dataframes/timeseries)
    ax = fig.add_subplot(nrows, ncols, i+1)
    building_id_dfs[i].plot(label = str(building_ids[i]))
    plt.legend()

This returns the following plot:

enter image description here

Another attempt also fails:

fig, axs = plt.subplots(3, 4)
for i in range(nrows):
    for j in range(ncols):

        axs[i+1, j+1].plot(building_id_dfs[i + j].index,  building_id_dfs[i + j], label = str(building_ids[i + j]))
    plt.legend()

No handles with labels found to put in legend.

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-93-2cc113304bb7> in <module>
      3     for j in range(ncols):
      4 
----> 5         axs[i+1, j+1].plot(building_id_dfs[i + j].index,  building_id_dfs[i + j], label = str(building_ids[i + j]))
      6     plt.legend()

IndexError: index 3 is out of bounds for axis 0 with size 3

enter image description here

How can I solve this issue?

Upvotes: 0

Views: 2500

Answers (1)

user8270077
user8270077

Reputation: 5071

I found this way:

fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
colors = ['#a6cee3','#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99','#b15928']
for i in np.arange(1, 13):
    ax = fig.add_subplot(3, 4, i)
    sns.lineplot(x =building_id_dfs[i-1].index , y = building_id_dfs[i-1],ax=ax, color = colors[i-1])
    ax.set_title('site_id: ' + str(site_id) + '   meter : ' + str(meter))
plt.show()

enter image description here

Upvotes: 2

Related Questions