0

I have 2 dataframes, containing same indexes and same column names (10 columns For example: from df1

   A  B  C
1  0  4  8
2  5  6  9
3  2  5  1

from df2:

   A  B  C
1  9  4  5
2  1  4  2
3  5  5  1

I want to plot on the same graph, column A from df1 vs column A from df2, column B from df1 vs column B from df2, etc..and this for every column. how could I do that with pandas and matplotlib

4
  • What kind of plot you are looking at? Commented Jun 27, 2019 at 6:41
  • just simple lines. I am plotting some ratio vs temperatures. I want to know how I can iterate on the whole set of columns and not write code for plotting for each pairs independantly Commented Jun 27, 2019 at 6:45
  • Do you want bar charts? Commented Jun 27, 2019 at 7:40
  • No thanks I needed lines Commented Jun 27, 2019 at 8:14

2 Answers 2

1

This is one of the way to do:

import pandas as pd
import matplotlib.pyplot as plt

d1 = {'A':[0,5,2],'B':[4,6,5],'C':[8,9,1]}
d2 = {'A':[9,1,5],'B':[4,4,5],'C':[5,2,1]}
df1 = pd.DataFrame(data=d1)
df2 = pd.DataFrame(data=d2)

df1_a = df1['A'].tolist()
df1_b = df1['B'].tolist()
df2_a = df2['A'].tolist()
df2_b = df2['B'].tolist()

plt.plot(df1_a, df1_b, 'r') 
plt.plot(df2_a, df2_b, 'b') 
plt.show()
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming that df1 and df2 be your dataframes you could use the below code which loops over all columns and saves the plots for you as well.

import matplotlib.pyplot as plt
import pandas as pd    
for column in df1.columns:
        x = df1[column]
        y = df2[column]

        if len(x) != len(y):
            x_ind = x.index
            y_ind = y.index
            common_ind = x_ind.intersection(y_ind)
            x = x[common_ind]
            y = y[common_ind]

        plt.scatter(x,y)
        plt.savefig("plot" +column+".png")
        plt.clf()

Hope this helps!

2 Comments

seems great but I have an issue. my x and y don't have the same size. for some data in y I don't have values in x. what should I do? is there a way to remove from y indexes that don't exist in x?
I have added a condition which checks if the size is same or not, if not then it will only pick only those indices which are common.

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.