0

So, I know similar questions have been posted, but nothing has worked for my particular case yet. I know it can be done with the Pandas plot function, but these lines need to be on a Matplotlib figure so they can be plotted with scatters and other things...

I have a DataFrame like this:

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

lines = pd.DataFrame(columns=list('ABC'))
lines.columns = ['T', 'Line1', 'Line2']
lines['T'] = np.arange(0,100,0.1)
lines['Line1'] = np.cos(lines['T']) + 30
lines['Line2'] = np.sin(lines['T']) + 13

And I want to make a plot with 2 separate lines that share the same X axis. I can do it like this:

plt.figure()
plt.plot(lines['T'], lines['Line1'])
plt.plot(lines['T'], lines['Line2'])
plt.show()

Which gives me:enter image description here

But, I'd like to do it via loop. Sorry if this has been answered somewhere else, but I couldn't find it. Any help would be appreciated! Thanks.

7
  • 2
    What do you mean by that you want to do it with a loop? Commented Aug 21, 2019 at 14:42
  • 3
    lines.plot(x='T')? Commented Aug 21, 2019 at 14:48
  • 1
    @QuangHoang That's a great little tip. Commented Aug 21, 2019 at 14:52
  • 1
    @QuangHoang this should be the answer. If you write it I will delete mine and upvote you Commented Aug 21, 2019 at 14:52
  • 1
    @KartikeyaSharma, it seems Cody does want the rest of the columns plotted according to his comment. That's why he wants a loop - so he doesn't have to keep adding .plot calls when new columns are added Commented Aug 21, 2019 at 14:56

3 Answers 3

1

By using the columns property of the dataframe.

plt.plot(lines[lines.columns[0]], lines[lines.columns[1:]])

Or simply as Quang Hoang suggested in a comment:

lines.plot(x='T')
Sign up to request clarification or add additional context in comments.

Comments

0

If you insist on using a loop then you can do something like this:

for column in lines:
    if column != 'T':
        plt.plot(lines['T'], lines[column])

1 Comment

Good to hear, although I suggest @QuangHoang's comment as a better solution, it's much more simpler and readable (even though it doesn't include iteration as originally requested in your question)
0
line_cols = ["Line1", "Line2"]

plt.figure()
for l in line_cols:
    plt.plot(lines['T'], lines[l])
plt.show()

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.