I had a similar question, which was answered previously. However, it differs in usage of Pandas package with it.
Here is my previous question: matplotlib - No xlabel and xticks for twinx axes in subploted figures
So, my question like last one is that why it does not show xlabel and xticks for first row diagrams when using this Python code.
Two notes:
- I also used
subplots
instead ofgridspec
but same result. - If you uncomment any of the commented lines in this code, which is related to using the Pandas on the axes in each diagram, the xlabel and xticks will disappear!
import matplotlib.pyplot as plt
import matplotlib.gridspec as gspec
import numpy as np
import pandas as pd
from math import sqrt
fig = plt.figure()
gs = gspec.GridSpec(2, 2)
gs.update(hspace=0.7, wspace=0.7)
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])
ax3 = plt.subplot(gs[1, 0])
ax4 = plt.subplot(gs[1, 1])
x1 = np.linspace(1,10,10)
ax12 = ax1.twinx()
ax1.set_xlabel("Fig1")
ax12.set_xlabel("Fig1")
ax1.set_ylabel("Y1")
ax12.set_ylabel("Y2")
# pd.Series(range(10)).plot(ax=ax1)
ax12.plot(x1, x1**3)
ax22 = ax2.twinx()
ax2.set_xlabel("Fig2")
ax22.set_xlabel("Fig2")
ax2.set_ylabel("Y3")
ax22.set_ylabel("Y4")
# pd.Series(range(10)).plot(ax=ax2)
ax22.plot(x1, x1**0.5)
ax32 = ax3.twinx()
ax3.set_xlabel("Fig3")
ax32.set_xlabel("Fig3")
ax3.set_ylabel("Y5")
ax32.set_ylabel("Y6")
# pd.Series(range(200)).plot(ax=ax3)
ax42 = ax4.twinx()
ax4.set_xlabel("Fig4")
ax42.set_xlabel("Fig4")
ax4.set_ylabel("Y7")
ax42.set_ylabel("Y8")
# pd.Series(range(10)).plot(ax=ax42)
plt.subplots_adjust(wspace=0.8, hspace=0.8)
plt.show()
I just got the same issue because I was mixing plots made with matplotlib and made with Pandas.
You should not plot with Pandas, here is how you could replace:
pd.Series(range(10)).plot(ax=ax42)
with
ax42.plot(pd.Series(range(10))
As Scimonster mentioned above for me it worked when I plotted all the pandas before creating twinx axes.
I had few plots in twinx which were also coming from Pandas Dataframe objects (x,t plots). I created separate lists before starting the plot and then used them to plot after plotting the first pandas plots.
to summarize my work flow was 1. Creating lists for twinx plots 2. opening plot and plotting all pandas plots with normal axes. 3. creating twinx axes 4. plotting lists on twinx axes
fortunately, this flow is working for me
来源:https://stackoverflow.com/questions/35249393/matplotlib-pandas-no-xlabel-and-xticks-for-twinx-axes-in-subploted-figures