0
$\begingroup$

I have two dataframes which each have n columns (changes depending input), where each dataframe represents an axis coordinate. Each column represents separate lines I want to plot.

Example dfs (1st being x coordinates, 2nd being y coordinates):enter image description here

I've looked at multiple threads on here and have tried to df.concat, create a df3 with tuple coordinates. The problem is that all the solutions often require plotting each column separately. However, I need this to be variable to the number of columns I generate based on my inputs.

My current code:

#Using datapull
from jdK_RS import RelStr, rsMOM
rs= RelStr
rsMO = rsMOM

#Remove first row and column so all points are plottable
rs = rs.iloc[1:,:]
rsMO = rsMO.iloc[1:,:]

#Create legend from the column headers 
legend = rs.columns.values.tolist()

#Combine the matrices to develop plots
rrg = pd.DataFrame()
rrg.reindex_like(rs)
rrg = pd.DataFrame({x: zip(rs[x], rsMO[x]) for x in rs.columns})

#Plot RRG
plt.plot(rrg)
plt.figure(figsize=(8,8))
plt.legend(legend)
plt.show()

When I plot a scatter, it plots the points correctly, but unfortunately does not create the separate lines I need for my analysis. As an example of the type of visual I'd like...

example from stockcharts.com

$\endgroup$

1 Answer 1

0
$\begingroup$

This how a did it:

Replicating your data:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data1=[
["2022-03-23",101.309106,99.773478,101.172967],

["2022-03-24",100.153241,102.079970,99.553582],

["2022-03-25",101.454518,100.903563,101.097076],

["2022-03-28",99.821442,101.924765,102.355196]
]

data2=[
["2022-03-23",100.740636,100.392111,100.974014],

["2022-03-24",100.578897,100.216871,99.600151],

["2022-03-25",102.463595,100.002197,101.820720],

["2022-03-28",100.216871,101.387072,101.605115]
]

columns=['Date','XLF','XLK','XLRE']
rs=pd.DataFrame(data1,columns=columns)
rsMO=pd.DataFrame(data2,columns=columns)

Dropping the first column(in your original code you dropped the first row):

rs = rs.iloc[:,1:]
rsMO = rsMO.iloc[:,1:]

Using iteritems():

for (column_name, column_data) in rs.iteritems():
    plt.plot(column_data,rsMO[column_name],'-o',label=column_name)
    plt.legend()
plt.figure(figsize=(8,8))
plt.show()

So, we iterate through the n columns of the rs dataframe, we get the column_name that we use as label, then we plot the pair formed by the column_data we got from rs and the data of the same column_name from the rsMO dataframe.

Pandas iteritems()

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.