-1

I try to plot several plots with multiple data series as subplots.

import pandas as pd
import matplotlib.pyplot as plt

df1 = pd.DataFrame({
    'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
    'index':[0, 1, 2, 3, 4], 
    '02K W':[3.5, 0.1, 3, 'nan', 0.2], 
    '03K W':[4.2, 5.2, 2.5, 3.0, 0.6], 
    '04K W':[1.5, 2.6, 8.2, 4.2, 5.3]}) 

df2 = pd.DataFrame({
    'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
    'index':[0, 1, 2, 3, 4], 
    '02K W':[3, 'nan', 5, 3, 5.2], 
    '03K W':[2.1, 2.9, 2.5, 3.9, 6.7], 
    '04K W':[1.8, 6.2, 5, 2.5, 3.7]}) 

df1['Date'] = pd.to_datetime(df1['Date'])
df1 = df1.set_index('index')

for col in df1.columns[1:]:
    plt.plot(df1['Date'], df1[col])

At the moment, I can only plot the first plot and I am not sure how I need to assign the for loop to the y-axis.

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(df1['Date'], y)
ax2.plot(df2['Date'], y)

Thanks a lot for the advise.

fjurt
  • 783
  • 3
  • 14

3 Answers3

2

Is this what you are looking for?

fig, (ax1, ax2) = plt.subplots(1, 2)
for col in df1.columns[1:]:
    ax1.plot(df1['Date'], df1[col])
    ax2.plot(df2['Date'], df2[col])
intedgar
  • 631
  • 1
  • 11
1

Something you can do in order to avoid having to use the axis syntax is call plt.sca(ax) which sets the current axis to ax. This is quite neat because you can explicitly set the axis you want to work with.

fig, (ax1, ax2) = plt.subplots(1, 2)
plt.sca(ax1)
plt.plot.plot(df1['Date'], y)
plt.sca(ax2)
plt.plot(df2['Date'], y)

There are many ways to navigate matplotlib and I find the above mentioned approach intuitive.

Kosmos
  • 497
  • 3
  • 11
1

You do not need to iterate across all the columns. Instead, parse them all directly. Look at this:

import pandas as pd

import matplotlib.pyplot as plt

df1 = pd.DataFrame({
    'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
    'index':[0, 1, 2, 3, 4], 
    '02K W':[3.5, 0.1, 3, 'nan', 0.2], 
    '03K W':[4.2, 5.2, 2.5, 3.0, 0.6], 
    '04K W':[1.5, 2.6, 8.2, 4.2, 5.3]}) 

df2 = pd.DataFrame({
    'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
    'index':[0, 1, 2, 3, 4], 
    '02K W':[3, 'nan', 5, 3, 5.2], 
    '03K W':[2.1, 2.9, 2.5, 3.9, 6.7], 
    '04K W':[1.8, 6.2, 5, 2.5, 3.7]}) 

df1['Date'] = pd.to_datetime(df1['Date'])
df1 = df1.set_index('index')
df2['Date'] = pd.to_datetime(df2['Date'])
df2 = df2.set_index('index')

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(25,8))
plot1 = ax1.plot(df1['Date'], df1[df1.columns[1:]])
ax1.set_xlabel('Date')
ax1.set_ylabel('W')
plot2 = ax2.plot(df2['Date'], df2[df2.columns[1:]])
ax2.set_xlabel('Date')
ax2.set_ylabel('W')

ax1.legend(plot1, df1.columns[1:])
ax2.legend(plot2, df2.columns[1:])
plt.show()
tzinie
  • 717
  • 5
  • 9