【问题标题】:matplotlib: same legend for two data setsmatplotlib:两个数据集的相同图例
【发布时间】:2020-07-31 19:24:06
【问题描述】:

我正在使用 matplotlib 在数据框中绘制两个数据集。数据集由不同的线型表示。以下是代码。

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.random.randn(10, 16))
df2 = pd.DataFrame(np.random.randn(10, 16))


plt.figure()
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 8))

df1.plot(ax=axes[0], style='-', legend=True)
axes[0].set_xlabel('x')
axes[0].set_ylabel('y')
axes[0].set_title('ttl')

df2.plot(ax=axes[0], style='--', legend=True)
axes[0].set_xlabel('x')
axes[0].set_ylabel('y')
axes[0].set_title('ttl')

plt.show()

但是,不同线型的颜色顺序是不同的。例如,line 中的 0 和 dashed line 中的 0 有不同的颜色。我想请教关于如何为两种线条样式获得相同颜色序列的建议。

编辑: 将输入更改为

df1 = pd.DataFrame(np.random.randn(501, 16))
df2 = pd.DataFrame(np.random.randn(5001, 16))

将图例更改为全蓝色

【问题讨论】:

    标签: python matplotlib colors comparison legend


    【解决方案1】:

    这是一个有点老套的解决方案,但您创建了一个与您的数据框长度相同的颜色列表,然后将这些颜色分配给每个图。

    from matplotlib import pyplot as plt
    import numpy as np
    import pandas as pd
    df1 = pd.DataFrame(np.random.randn(10, 6))
    df2 = pd.DataFrame(np.random.randn(10, 10))
    
    fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 8))
    
    # to account for different numbers of columns between dfs
    if len(df2) > len(df1):
        colors = plt.cm.jet(np.linspace(0,1,len(df2)))
    else:
        colors = plt.cm.jet(np.linspace(0,1,len(df1)))
    
    df1.plot(ax=axes[0], style='-', color = colors, legend=True)
    axes[0].set_xlabel('x')
    axes[0].set_ylabel('y')
    axes[0].set_title('ttl')
    
    df2.plot(ax=axes[0], style='--', color = colors, legend=True)
    axes[0].set_xlabel('x')
    axes[0].set_ylabel('y')
    axes[0].set_title('ttl')
    
    plt.show()
    

    【讨论】:

    • 非常感谢您的回答。但是当 len(df1) 和 len(df2) 不同时它不起作用
    • 如果长度不同,那么我认为您可以将颜色序列作为长度中较长的一个。我现在试试
    • 谢谢你,它似乎工作。我认为问题出在其他问题上,可能与我的实际数据有关。我不知道为什么它不起作用
    • 更新了我的答案,图例可以有不同的长度,但如果图例条目太多,它可能会被删掉
    • 在这种情况下,我们可以使用 if else ,如您的回答中所建议的那样
    猜你喜欢
    • 2015-06-09
    • 2012-09-27
    • 1970-01-01
    • 2015-12-22
    • 2016-06-14
    • 1970-01-01
    • 2011-05-15
    • 2021-07-30
    • 1970-01-01
    相关资源
    最近更新 更多