1

I have two dataFrames that I would like to plot into a single graph. Here's a basic code:

#!/usr/bin/python

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

scenarios = ['scen-1', 'scen-2']

for index, item in enumerate(scenarios):
    df = pd.DataFrame({'A' : np.random.randn(4)})
    print df

df.plot()
plt.ylabel('y-label')
plt.xlabel('x-label')
plt.title('Title')
plt.show()

However, this only plots the last dataFrame. If I use pd.concat() it plots one line with the combined values. How can I plot two lines, one for the first dataFrame and one for the second one?

2
  • Could you provide an image of what you mean by two plots in one graph? What I understand is that you want two or more plots in one figure, am I right? But also I saw the comment you made to one of the answers that you want both plots as if it was one, and I don't seem to understand what you want. Do you want a graph were one 'x value' has multiple 'y values'? Like in a candlestick chart? Commented Jan 9, 2018 at 18:03
  • There's a question I have already answered about multiple plots in one figure, have a look: stackoverflow.com/questions/48125674/… Commented Jan 9, 2018 at 18:05

2 Answers 2

3

You need to put your plot in the for loop.

If you want them on a single plot then you need to use plot's ax kwarg to put them to plot on the same axis. Here I have created a fresh axis using subplots but this could be an already populated axis,

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

scenarios = ['scen-1', 'scen-2']

fig, ax = plt.subplots()

for index, item in enumerate(scenarios):
    df = pd.DataFrame({'A' : np.random.randn(4)})
    print df
    df.plot(ax=ax)

plt.ylabel('y-label')
plt.xlabel('x-label')
plt.title('Title')
plt.show()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Josh. But putting df.plot() inside the loop yield two plots. I want both on the same plot.
@AdhySatya editted to include this - i see it in your question now :)
@josh that worked, thanks. I made a small fix, it should be subplots()
0

The plot function is only called once, and as you say this is with the last value of df. Put df.plot() inside the loop.

Comments

Your Answer

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