1

do you know how I can graph multi-data frames in python at the same time in a loop, now, I need to repeat the same structure but is very inefficient if I have n data frames? ...

df_0.plot(kind='line',y='AB',ax=ax)
df_1.plot(kind='line',y='AB',ax=ax)
df_2.plot(kind='line',y='AB',ax=ax)
plt.legend(['sim 1', 'sim 2', 'sim 3'], loc= 0)
plt.show()
..
.
(...)


The code that I create is this:

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

def t(i):
    global a, b, c
    if i == 0:
        a = pd.DataFrame(np.random.randint(low=0, high=10, size=(2, 2)), columns=['a', 'b'])
        return a
    elif i == 1:
        b = pd.DataFrame(np.random.randint(low=0, high=10, size=(2, 2)), columns=['a', 'b'])
        return b
    else:
        c = pd.DataFrame(np.random.randint(low=0, high=10, size=(2, 2)), columns=['a', 'b'])
        return c

dfnames = ['df0', 'df1', 'df2']
for x in dfnames: exec(x + ' = t(x)', globals()) # generate multiple dataframes and assign the names globaly 

#to plot

ax = plt.gca()
df0.plot(kind='line',x='b',y='a', color='red', ax=ax)
df1.plot(kind='line',x='b',y='a', color='green', ax=ax)
df2.plot(kind='line',x='b',y='a', color='blue', ax=ax)
plt.show()

I'm trying to do this to fix that with a loop, but python returns me this error, how can I do that?

a = plt.gca()
for w in dfnames:
    w.plot(x='a', y='b', kind='line', ax=a)
    plt.show()
Traceback (most recent call last):
  File "...py", line 67, in <module>
    w.plot(x='a', y='b', kind='line')
AttributeError: 'str' object has no attribute 'plot'

Thanks a lot for your amazing help!

1 Answer 1

1

with the time: I found a quick solution and is write the global variables into a list, but I'd like to do a generalization with multiple data frames or convert these global variables defined previously in exec() method in a list to plot all together ...

any ideas?

ds = [df0, df1, df2, df3 ....] # I need to write again this line...
ax = plt.gca()
for x in ds:
    x.plot(kind='line', y='1', ax=ax)  # generate multiple dataframes
plt.show()

Sign up to request clarification or add additional context in comments.

Comments

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.