1

I have a data frame whose data I want to plot in a 2 x 1 subplot. The 1st subplot has two y-axes, the 2nd one has only one:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame()
df['Time__min'] = [0, 1, 2, 3, 4]
df['Data1']     = [2, 1, 4, 3, 5]
df['Data2']     = [5, 3, 2, 4, 1]
df['Data3']     = [4, 1, 3, 2, 5]

fig, axes = plt.subplots(nrows=2, ncols=1)
ax = df.plot(x = 'Time__min', y = 'Data1', ax=axes[0])
ax.set_xlabel(xlabel = 'min')
ax.set_ylabel(ylabel = '°C')
ax2 = df.plot(x = 'Time__min', y = 'Data2', secondary_y=True, ax=ax, style = '--')
ax2.set_xlabel(xlabel = 'min') 
ax2.set_ylabel(ylabel = 'bar') 
      
ax3 = df.plot(x = 'Time__min', y = 'Data3', ax=axes[1])
ax3.set_xlabel(xlabel = 'min')
ax3.set_ylabel(ylabel = '(kg/s)') 

plt.show()

enter image description here

The x-axis of the 1st subplot shows neither numbers nor the label ("min"). How can I make the x-axis of the 1st subplot look exactly like the one of the 2nd subplot?

Adding plt.setp(axes[0].get_xticklabels(), visible=True) before plt.show() as recommended here has not done the trick for me. Neither did adding fig.tight_layout() as recommended here.

Edit: It looks like the secondary y-axis is causing the issue as shown here. Unfortunately, the proposed solution does not work for me (see above). Does anybody have another idea?

Dave
  • 171
  • 2
  • 13
  • Adding `fig.tight_layout()` gives me https://i.stack.imgur.com/y9lI7.png, matplotlib 3.5.1 and pandas 1.4.1. What versions do you have? – BigBen Apr 19 '22 at 16:11
  • 1
    You might try `plt.subplots(nrows=2, ncols=1, sharex=False)`. Anyway, the plot shown seems to be using some non-standard settings (normally, to not have the top and right spine, you need to explicitly hide them). – JohanC Apr 19 '22 at 16:16
  • @BigBen: I have matplotlib 3.3.2 and pandas 1.1.3. Adding `fig.tight_layout()` does not help here. – Dave Apr 19 '22 at 16:19
  • @JohanC: Correct, I have an MPL stylesheet in place that removes top and right spine, adds grid, and changes color and width of the lines. However, it should not mess with the formatting of the axes. – Dave Apr 19 '22 at 16:20
  • @JohanC `sharex=False` does not help in my case. However, `sharex=True` is a reasonable workaround for my issue. I didn't know about that one. Thanks! – Dave Apr 19 '22 at 16:24
  • @Dave it might be a problem related with the "old" matplotlib version. I'm using v3.5.1 and the plot appears correct! – Davide_sd Apr 19 '22 at 17:11

0 Answers0