0
votes

I am trying to plot three histograms side-by-side (one row, 3 columns) by using a for loop and iterating over the same code but for a different column. I found two different methods, one is to use the plt.subplots(1, 3, i) and then iterate over i, and the other is to explicitly set fig, ax = plt.subplots() and replace each plt with ax[i] and iterate over that.

However neither of these works properly because of the additional lines I plot on the histogram(s).

How could I make this code work for side-by-side plots?

for parameter in ['k', 'm', 'sig']:

        plt.hist(df[parameter], density=True, bins=20, label=parameter, ec='black')
        mn, mx = plt.xlim()
        plt.xlim(mn, mx)
        kde_xs = np.linspace(mn, mx, 301)
        kde = st.gaussian_kde(df[parameter])
        plt.plot(kde_xs, kde.pdf(kde_xs), label="PDF")
        plt.legend(loc="upper left")
        plt.ylabel('Frequency')
        plt.xlabel([parameter])
        plt.title(f"Histogram for bootstrapped: {parameter}")
        plt.axvline(df[parameter].mean(), color='r', linestyle='solid', 
        linewidth=2)
1
Is your issue implementing Axes.axvline then? - BigBen
A few issues, one is plt.xlim, if I implement ax[i].xlim then it doesn't work. Another issue is the plt.title which won't work with ax[i].title. Axvline seems to work fine. I guess I would be looking for a general method that avoids completely changing the code. I feel like I am missing some easy trick. - MilTom
See also The Lifecycle of a Plot about the two different APIs. - JohanC
Great, feel free to post the revised code as an answer! - BigBen

1 Answers

0
votes

I just had to do the below. Use the axes[i] on everything and the zip function to iterate over histograms.

    fig, axes = plt.subplots(1, 3, figsize=(26, 7))
    for parameter, i in zip(['k', 'm', 'sig'], [0, 1, 2]):

        axes[i].hist(data[parameter].dropna(), density=True, bins=20, label=parameter, ec='black')
        mn, mx = axes[i].set_xlim()
        axes[i].set_xlim(mn, mx)
        kde_xs = np.linspace(mn, mx, 301)
        kde = st.gaussian_kde(data[parameter].dropna())
        axes[i].plot(kde_xs, kde.pdf(kde_xs), label="PDF")
        axes[i].legend(loc="upper left")
        axes[i].set_ylabel('Frequency')
        axes[i].set_xlabel([parameter])
        axes[i].set_title(f"Histogram for bootstrapped: {parameter}")
        axes[i].axvline(data[parameter].dropna().mean(), color='r', linestyle='solid', linewidth=2)