p3hndrx
p3hndrx

Reputation: 107

Subplots with specific Columns from Single Dataframe

I am so close.. I have a dataframe that looks like:

      date    gpa   use   dev
  20210614  52.50  2.30  2.49
  20210616  52.43  2.28  2.47
  20210623  53.41  2.41  2.57
  20210630  55.98  2.33  2.58

I can plot a single line chart to file with:

outpath = "/tmp/"
df.plot(x='date',y='gpa',kind='line').get_figure().savefig(outpath)

However, I would like to draw a subplot, with each column: gpa, use, dev against my date column.

I also tried this, which plots a single chart to file with all 3 series on the same x-y:

df.plot(x='date')
plt.subplot().getfigure().savefig(outpath)

As you can see from the source data, use and dev columns are much smaller scale. How can I go about plotting each on their own y-axis e.g. 3x smaller charts on the same output?

I'm not sure where to start.

Thanks in advance!

Upvotes: 0

Views: 1058

Answers (1)

Henry Ecker
Henry Ecker

Reputation: 35686

Add subplots=True to DataFrame.plot and do not specify a y value:

import pandas as pd
from matplotlib import pyplot as plt

df = pd.DataFrame({
    'date': [20210614, 20210616, 20210623, 20210630],
    'gpa': [52.5, 52.43, 53.41, 55.98],
    'use': [2.3, 2.28, 2.41, 2.33],
    'dev': [2.49, 2.47, 2.57, 2.58]
})

df.plot(x='date', kind='line', subplots=True)
plt.tight_layout()
plt.show()

plot 1 int xaxis


Optional convert date to_datetime for clearer x-axis ticks:

df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')
df.plot(x='date', kind='line', subplots=True)
plt.tight_layout()
plt.show()

plot 2 datetime xaxis

Upvotes: 2

Related Questions