Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple csv files plotted on same axis with different colors

Consider the following csv files

import pandas as pd
from io import StringIO
from matplotlib import pylab as plt

csv1 = """x,y
0,1
1,0"""

csv2 = """x,y
0,0
1,1"""

csv3 = """x,y
.5,1
.5,0"""

csv4 = """x,y
0,.5
1,.5"""

I can plot them all on different axes

fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
for i, csv in enumerate([csv1, csv2, csv3, csv4]):
    r, c = i // 2, i % 2
    pd.read_csv(StringIO(csv)).plot.scatter('x', 'y', ax=axes[r, c])

fig.tight_layout()

enter image description here

But how do I plot on same axis with different colors?

like image 335
piRSquared Avatar asked Mar 03 '26 22:03

piRSquared


1 Answers

a. Using matplotlib

matplotlib uses different colors automatically

fig, axes = plt.subplots()
for i, csv in enumerate([csv1, csv2, csv3, csv4]):
    df = pd.read_csv(StringIO(csv))
    axes.scatter(df.x, df.y)

fig.tight_layout()
plt.show()

enter image description here

b. Using pandas

One would need to define a list of colors to use.

colors = ["blue", "orange", "green", "red"]
fig, axes = plt.subplots()
for i, csv in enumerate([csv1, csv2, csv3, csv4]):
    df = pd.read_csv(StringIO(csv)).plot.scatter('x', 'y', ax=axes, color=colors[i])

fig.tight_layout()
plt.show()

enter image description here

like image 52
ImportanceOfBeingErnest Avatar answered Mar 05 '26 13:03

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!