0

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: enter image description here

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: enter image description here

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!

1 Answer 1

2

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:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Aah so simple! Thank you very much, it works perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.