Liza
Liza

Reputation: 971

How to control the color of graph lines in matplotlib?

I have a following data frame of paths, (x,y) points belonging to the same "uid" is considered to be one separate path.

   uid        x       y
 0  5          1       1
 1  5          2       1
 2  5          3       1
 3  5          4       1
 4  21         4       5 
 6  21         6       6
 7  21         5       7
 8  25         1       1
 9  25         2       2
10  25         3       3
11  25         4       4
12  25         5       5
13  27         1       3
14  27         2       3
15  27         4       3

Following is the code I am using to plot each of these paths:

%matplotlib notebook

fig, ax = plt.subplots(figsize=(12,8))
df.groupby("uid").plot(kind='line', x = "x", y = "y", ax = ax)
plt.title("Paths")

#ax.legend_.remove()

plt.show()

Since, matplotlib auto generates the color for each line in the graph, I want to control the color of the paths generated from my df based on their "uid".

Suppose I want to keep the color of the path generated for uid=25 and uid=27 only to be green and the rest of them to be black.

Also, I want to change the "kind" of line for uid=25,27 to be dotted while all others should be simple line. How can I achieve this?

Upvotes: 1

Views: 814

Answers (1)

David Jaimes
David Jaimes

Reputation: 341

This is how you would do it as a loop:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_table("data.txt", sep=" ")
fig, ax = plt.subplots(figsize=(12, 8))

color = ["k", "g"]
line = ["solid", "dotted"]
for (key, gr) in df.groupby("uid"):
    if key == 25 or key == 27:
        i = 1
    else:
        i = 0
    gr.plot(linestyle=line[i], x="x", y="y", ax=ax, color=color[i], label=key)
plt.title("Paths")
plt.show()

enter image description here

Upvotes: 1

Related Questions