假设我有一个图 A 由 10 行组成:1 到 10,根据 matplotlib 的默认设置着色。
现在我想绘制图 B 中的第 1-5 行和图 C 中的第 6-10 行,但要使线条的颜色保持一致。我的意思是在图 B 中,第 1-5 行的颜色与图 A 中的第 1-5 行相同;图C中第6-10行颜色与图A中第6-10行颜色相同。
有没有办法做到这一点?提前致谢!
请您参考如下方法:
如果您通过分配标签来链接您的绘图(如果您有图例,这很有用),那么您可以查找以前的颜色。
原始问题:
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")
