Reputation: 49
I have a dataframe df
with a few meteorological parameters in it. The dataframe has DatetimeIndex, so when I plot it, it automatically puts the time on the x axis. Now that is great, because when I plot one parameter, for example:
ax1 = df.plot(y='temp_vaisala' , color='tab:blue')
ax1.set_ylabel('Temerature (C)', color='tab:blue')
ax1.set_xlabel('Month', color='tab:blue')
It gives me the following nice graph as a result:
However, I would like to have a graph with two parameters, so I use the twinx option like this:
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')
This function however gives the following graph as a result:
So for some reason, this completely messes up the description under the x axis. I would like this graph with two parameters to have the same x axis as the first graph. Does anyone have a solution for this? Many thanks in advance!
Upvotes: 0
Views: 579
Reputation: 153460
Try this, using pandas plot:
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');
Output:
Upvotes: 2