Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show different colors on a plot for values from different columns

Please consider the small dataframe test:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
         [
             [1, 1.0, 0.0, 0.0],
             [1, 0.75, 0.25, 0.0],
             [1, 0.576, 0.396, 0.028]
         ],
         columns = ["State", "1", "2", "3"]
    )

I am now plotting the 3 last columns by:

fig = plt.figure()
ax = plt.subplot()

ax.plot(df[["1","2","3"]], label = ["1 (from 1)","2 (from 1)","3 (from 1)"], 
        color = "red", marker = ".", linestyle="-")
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5),
          fancybox=True, shadow=True)
plt.show()

What would be the easiest way to show a different color for each column of data, such as "red" for column 1, "blue" for column 2 and green for column 3 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would say that the easiest way would be to use the built-in plot.

Otherwise, you need to loop :

fig, ax = plt.subplots()

colors = ["red", "blue", "green"]
labels = ["1 (from 1)","2 (from 1)","3 (from 1)"]

for idx, col in enumerate(["1", "2", "3"]):
    ax.plot(df[col], label=labels[idx], color=colors[idx], marker=".", linestyle="-")

ax.legend(loc="center left", bbox_to_anchor=(1, 0.5),
          fancybox=True, shadow=True)
plt.show();

Output :

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading