-2

I have some data organized with columns like this: time1, value1, time2, value2, time3, value3 and so on. These are the names of the columns, but they do not have headers. The data starts as numbers and is identified separately in the document. I can graph the first pair of data fine, but I do not know how to get multiple plots to appear on the same graph.

My code looks like this

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('exp_200_ALD_current.csv', skiprows=35, usecols=[0, 1], index_col=0)
print(df.head())
df.plot(legend=False, title="Current density vs. Time", xlabel="Time (h)", ylabel="Current density (mA/cm^2)")
plt.show()

Which as expected produces a plot of the first time and value. I would like all of them to appear on the same graph.

qazwsx123
  • 7
  • 3
  • Another possible duplicate: https://stackoverflow.com/q/64038060/12131013 – jared Aug 02 '23 at 14:58
  • My columns aren't named above the data. The names occur elsewhere. Do I have to write names above them in excel or similar? – qazwsx123 Aug 02 '23 at 15:05
  • If they're named in the original CSV then you can use those. Otherwise, after importing all the data you can set the column names by doing `df.columns = [list of column names in order]`. See: https://stackoverflow.com/a/29442472/12131013 – jared Aug 02 '23 at 15:07
  • Okay I almost have it. When I try to name the columns, I get a length mismatch. It's not naming the leftmost column, only the ones after it. Is there anything I can do to fix this? – qazwsx123 Aug 02 '23 at 15:15
  • I see you're setting the 0th column as the index, so that would be named separately. See [this answer](https://stackoverflow.com/a/19851521/12131013) for how to rename the index. – jared Aug 02 '23 at 15:26
  • To clarify things, are the time columns all identical or different? – jared Aug 02 '23 at 15:29
  • Figured it out, thanks for everything! I was using someone's code, and I didn't understand what it was doing. I removed using the first column as an index, and now I can plot columns against each other, using the solution provided by the other commenter. Naming the columns helped. – qazwsx123 Aug 02 '23 at 15:34

1 Answers1

-1

Use the same axis:

ax = df.plot(x="time1",y="value1")
df.plot(x="time2",y="value2",ax=ax)
df.plot(x="time3",y="value3",ax=ax,xlabel="Time (h)", ylabel="Current density (mA/cm^2)")
not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • My columns are not explicitly labeled like this and do not occur at the beginning of the file. Is this possible to do with column numbers and row skip? – qazwsx123 Aug 02 '23 at 15:00
  • So keep reading just the columns you need but continue to use `ax=ax` as an argument when you `plot` – not_speshal Aug 02 '23 at 15:03
  • Thank you! I'm almost able to make it work. I've gotten the plots on the same axis, now just working on making the first column a regular column and not an index so I can plot it too. – qazwsx123 Aug 02 '23 at 15:28