NoNam4
NoNam4

Reputation: 597

Matplotlib subplot using for loop Python

Trying to create multiple charts and save it as one image. I managed to combine multiple charts but there is couple things that going wrong. Could not set tittles for all charts only for last one for some reason. Also numbers is not showing in full as last chart. Also want to change colors for line(white), labels(white), background(black) and rotate a date so it would be easily to read it. enter image description here

dataSet = {"info":[{"title":{"Value":[list of data]}},{"title":{"Value":[list of data]}}, 
...]}

fig, ax = plt.subplots(2, 3, sharex=False, sharey=False, figsize=(22, 10), dpi=70, 
linewidth=0.5)
ax = np.array(ax).flatten()

for i, data in enumerate(dataSet['info']):
    for key in data:
        df: DataFrame = pd.DataFrame.from_dict(data[key]).fillna(method="backfill")
        df['Date'] = pd.to_datetime(df['Date'], unit='ms')
        df.index = pd.DatetimeIndex(df['Date'])
        x = df['Date']
        y = df['Value']
        ax[i].plot(x, y)
    current_values = plt.gca().get_yticks()
    plt.gca().set_yticklabels(['{:,.0f}'.format(x) for x in current_values])
    plt.title(key)

plt.show()

Upvotes: 3

Views: 2017

Answers (1)

Carlos Horn
Carlos Horn

Reputation: 1293

Your figure consists of the various axes objects. To set the title for each plot you need to use the corresponding axes object, which provides the relevant methods you need to change the appearance. See for example:

import matplotlib.pyplot as plt
import numpy as np

fig, axarr = plt.subplots(2, 2)

titles = list("abcd")

for ax, title in zip(axarr.ravel(), titles):
    x = np.arange(10)
    y = np.random.random(10)
    ax.plot(x, y, color='white')
    ax.set_title(title)
    ax.set_facecolor((0, 0, 0))
    
fig.tight_layout()

In order to change labels, show the legend, change the background, I would recommend to read the documentations. For the dates, you can rotate the labels or use fig.autofmt_xdate().

Upvotes: 2

Related Questions