【问题标题】:How to control the color of graph lines in matplotlib?matplotlib中如何控制图形线的颜色?
【发布时间】:2017-11-12 15:35:58
【问题描述】:

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

   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

以下是我用来绘制这些路径的代码:

%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 自动为图中的每条线生成颜色,我想根据路径的 "uid" 控制从我的 df 生成的路径的颜色。

假设我想保持为 uid=25uid=27 only 生成的路径的颜色为 green 其余为黑色。

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

【问题讨论】:

    标签: python pandas matplotlib dataframe graph


    【解决方案1】:

    这就是你将如何做一个循环:

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

    【讨论】:

    • 谢谢,但是上面的df不仅限于四个id,我的实际数据框有100个路径,我希望所有的行都是相同的颜色,除了几个id是特定的颜色,如上面为 uid 25 和 27 生成的示例路径应为绿色,其余应为黑色。
    • @Liza 我用正确的解决方案编辑了 David 的帖子,所以只要他或具有适当权限的人批准它就应该可见。
    • @Hami 非常感谢。但是,如果很快没有人批准它,请将其作为单独的答案发布。
    • @Liza 立即查看帖子。
    • 嗨@Liza,我提供了关于线条样式的最后一点信息(实线与虚线)。
    猜你喜欢
    • 2010-12-27
    • 2018-02-01
    • 2019-03-23
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2018-04-30
    相关资源
    最近更新 更多