Search code examples
pythonmatplotlibseabornsubplot

How to correct my misunderstandings of subplots


I seemed to understand how the subplots and ax options work in Matplotlib, but I just did a graphical test and it doesn't work at all as expected, which shows me that I still don't quite understand the syntax of the statements.

The program is below; I should get 2 separate graphs but there is only 1, which seems to overlay the 2 datasets.

[NOTE: the code must use sns.histplot; the p1 and p2 data do not correspond to the reality of the data to be presented.]

Could you explain to me what my typing errors are?

p1 = [7.86706728, 2.07023424, 8.59099644, 7.07850226, 9.79575806]
p2 = [1.48705512, 0.3142216 , 0.3407479 , 0.32947036, 0.32947036]

fig, ax = plt.subplots(1, 2, figsize = (8,3), tight_layout = True)

ax[0] = sns.histplot(data = None, x = p1, bins = 25, discrete = False, shrink = 1.0,
             stat = "probability", element = "bars", color = "green", kde = False) 

ax[0].set_title("p1", fontsize = '15')
ax[0].set_xlabel("p1" , fontsize = '15')
ax[0].set_ylabel("Probability", fontsize = '15')

ax[1] = sns.histplot(data = None, x = p2, bins = 25, discrete = False, shrink = 1.0,
             stat = "probability", element = "bars", color = "green", kde = False) 

ax[1].set_title("p2", fontsize = '15')
ax[1].set_xlabel("p2" , fontsize = '15')
ax[1].set_ylabel("Probability", fontsize = '15')

plt.show()

Wrong output: enter image description here


Solution

  • Your problem is in the way you are using the seaborn histogram plotting. From its documentation (here), you can provide, as argument, a pre-existing axes. If not provided, seaborn will call plt.gca() (get current axes). As you are not providing an ax as an argument in your code, both calls of sns.histplot() will call plt.gca(). But, the current axes, is ax[1], so it is the axes selected for both histogram calls.

    So, your first call should be:

    sns.histplot(ax = ax[0], ...) # and the rest of the arguments
    

    And the second:

    sns.histplot(ax = ax[1], ... ) # and the rest of the arguments