在matplotlib中,是否可能在不同的绘图中保持相同行的颜色相同?

4
我有一个由10条线组成的图形A: 1至10,使用matplotlib的默认设置进行着色。
现在我想在图形B中绘制1-5条线,在图形C中绘制6-10条线,但保持线条颜色一致。我的意思是在图形B中,线条1-5的颜色与图形A中的1-5线条相同;在图形C中,线条6-10的颜色与图形A中的6-10线条相同。
有什么办法可以做到这一点吗?谢谢!
2个回答

2
如果您通过分配标签来连接您的图形(如果您已经有一个图例,这很有用),那么您可以查找先前的颜色。
原始问题:
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np


f, axs = plt.subplots(3)

lines = [np.random.rand(10,1) for a in range(10)]

for i, line in enumerate(lines):
    axs[0].plot(line)

for i, line in enumerate(lines[:5]):
    axs[1].plot(line)

for i, line in enumerate(lines[5:]):
    axs[2].plot(line)

axs[0].set_title("All Lines")
axs[1].set_title("First Five")
axs[2].set_title("Last Five")
f.tight_layout()
plt.savefig("No Linking.png")

不要链接颜色

然后添加一些标签:

f, axs = plt.subplots(3)

for i, line in enumerate(lines):
    label = "Line {}".format(i)
    axs[0].plot(line, label=label)

for i, line in enumerate(lines):
    if i < 5:
        ax = axs[1]
    else:
        ax = axs[2]

    label = "Line {}".format(i)
    # here we look up what colour was used in the first subplot.
    colour = [l for l in axs[0].lines if l._label == label][0]._color
    ax.plot(line, label=label, color=colour)



axs[0].set_title("All Lines")
axs[1].set_title("First Five")
axs[2].set_title("Last Five")
f.tight_layout()
plt.savefig("With Linking.png")

enter image description here


-2

对于第6-10行,只需在绘制实际行之前绘制5个空白行。1-5将已经具有与1-10方案相匹配的默认颜色。

import matplotlib.pyplot as plt
plt.plot([0]) # line 1
plt.plot([0]) # line 2
plt.plot([0]) # line 3
plt.plot([0]) # line 4
plt.plot([0]) # line 5
plt.plot([1,2,3,4]) # line 6
plt.ylabel('some numbers')
plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接