matplotlib:两个数据集的相同图例

matplotlib: same legend for two data sets

我正在使用 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))

将图例更改为全蓝色

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

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