如何控制matplotlib中图线的颜色? [英] How to control the color of graph lines in matplotlib?

查看:351
本文介绍了如何控制matplotlib中图线的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下面的路径数据框,属于同一个uid的(x,y)点被认为是一个单独的路径。

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()

因为matplotlib auto会自动为图形中的每一行生成颜色,所以我想根据它的uid控制从df生成的路径的颜色。

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".

假设我想保留为 uid = 25 uid = 27 生成的路径的颜色成为绿色,其余成员为黑色。

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.

另外,我想将uid = 25,27的行的kind更改为虚线而所有其他人应该是简单的线路。我怎样才能做到这一点?

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?

推荐答案

这就是你如何做到这一点的循环:

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()

这篇关于如何控制matplotlib中图线的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆