Home > Software engineering >  Two pandas dafatrame column with common Y values plotted in the same figure
Two pandas dafatrame column with common Y values plotted in the same figure

Time:06-29

I have a dataframe with a Seconds, SYS and DIA columns.

import pandas as pd
data={'Seconds':[10,20,30,40],'SYS':[95,103,99,112],'DIA':[56,75,62,70]}
df = pd.DataFrame(data)

Seconds is the column with the number of seconds since the start of the experiment (integer) and should be used to build the timeseries X axis.

SYS and DIA are are two columns with respectively the systolic and diastolic bllod pressure expressed in mmHg.

For every timestamp there are always both a systolic and diastolic readings.

I am trying to plot this dataframe in only one figure with the SYS values in red and the DIA values in BLUE, but they are output in two different figures. What's wrong with the following code:

plt.figure(figsize=(14,6))
ax1 = df.plot.scatter(x='elapsed_seconds', y='SYS', color='red', grid=True, label='SYS')
ax1 = df.plot.scatter(x='elapsed_seconds', y='DIA', color='blue', grid=True, label='DIA')
plt.legend()
plt.legend(loc='upper left')
plt.xticks(rotation=45)
ax1.set_xlabel('time (seconds)')
plt.show()

Ideally I would like every pair of SYS and DIA values measured at a specific Second to be connected by a vertical line, but this I don't have any idea on how to achieve.

Thanks

CodePudding user response:

You can try the following code snippet.

Code:

import pandas as pd
import matplotlib.pyplot as plt


data={'Seconds':[10,20,30,40],'SYS':[95,103,99,112],'DIA':[56,75,62,70]}
df = pd.DataFrame(data)
fig, ax = plt.subplots(figsize=(14,6))

ax1 = df.plot.scatter(x='Seconds', y='SYS', color='red', grid=True, label='SYS', ax=ax)
ax1 = df.plot.scatter(x='Seconds', y='DIA', color='blue', grid=True, label='DIA', ax=ax)
plt.legend()
plt.legend(loc='upper left')
plt.xticks(rotation=45)
ax1.set_xlabel('time (seconds)')
plt.show()

Output: output image

  • Related