twinx绘图中Python x轴的变化
我有一个数据帧twinx绘图中Python x轴的变化,python,matplotlib,Python,Matplotlib,我有一个数据帧df,里面有一些气象参数。数据帧有DatetimeIndex,所以当我绘制它时,它会自动将时间放在x轴上。这很好,因为当我绘制一个参数时,例如: ax1 = df.plot(y='temp_vaisala' , color='tab:blue') ax1.set_ylabel('Temerature (C)', color='tab:blue') ax1.set_xlabel('Month', color='tab:blue') 结果,我得到了以下漂亮的图表: 但是,我希望有一
df
,里面有一些气象参数。数据帧有DatetimeIndex,所以当我绘制它时,它会自动将时间放在x轴上。这很好,因为当我绘制一个参数时,例如:
ax1 = df.plot(y='temp_vaisala' , color='tab:blue')
ax1.set_ylabel('Temerature (C)', color='tab:blue')
ax1.set_xlabel('Month', color='tab:blue')
结果,我得到了以下漂亮的图表:
但是,我希望有一个带有两个参数的图形,因此我使用twinx选项,如下所示:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(df['temp_vaisala'], 'tab:blue')
ax2.plot(df['rel_humidity_vaisala'], 'b-')
ax1.set_xlabel('Month', color='tab:blue')
ax1.set_ylabel('Temerature (C)', color='tab:blue')
ax2.set_ylabel('RH (-)', color='b')
但是,该函数的结果如下所示:
所以出于某种原因,这完全搞乱了x轴下的描述。我希望这个有两个参数的图与第一个图具有相同的x轴。有人能解决这个问题吗?非常感谢 尝试使用熊猫图:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({'temp':np.arange(12),'rhel':np.arange(220,100,-10)},
index=pd.date_range('10-01-2020', periods=12, freq='MS'))
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
df['temp'].plot(ax = ax1, color='tab:blue')
df['rhel'].plot(ax = ax2, color='b')
ax1.set_xlabel('Month', color='tab:blue')
ax1.set_ylabel('Temerature (C)', color='tab:blue')
ax2.set_ylabel('RH (-)', color='b');
输出:
尝试使用熊猫图:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({'temp':np.arange(12),'rhel':np.arange(220,100,-10)},
index=pd.date_range('10-01-2020', periods=12, freq='MS'))
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
df['temp'].plot(ax = ax1, color='tab:blue')
df['rhel'].plot(ax = ax2, color='b')
ax1.set_xlabel('Month', color='tab:blue')
ax1.set_ylabel('Temerature (C)', color='tab:blue')
ax2.set_ylabel('RH (-)', color='b');
输出:
啊,太简单了!非常感谢,它工作得非常好!啊,太简单了!非常感谢,它工作得非常好!