Matplotlib:不同颜色的点和线的图例

时间:2019-07-12 22:02:59

标签: matplotlib

请参见以下代码:

import matplotlib.pyplot as plt
import numpy as np
from pylab import *

graph_data = [5, 8, 7, 9]
x = range(len(graph_data))
y = graph_data
fig, ax = plt.subplots()

# Comment the following two lines
plt.plot(x, y, markersize=6, color='g', label='blah 1')
plt.plot(x, y, 'ob', markersize=6, label='blah 2')

# ...and uncomment the following line
#plt.plot(x, y, '-ob', markersize=6, label='blah')

ax.legend()
plt.show()
filename = 'test2.pdf'
fig.savefig(filename, bbox_inches='tight')

我要实现的是,点(o)和连接它们的线段(-)的颜色分别是不同的。我能够得到它:

但是,当我尝试为其分配标签时(在图例中),问题就白了。我得到以下形式的图例:

...而我想要这种形式:

后面的图例可以通过注释两行plot并取消注释下面的plot行来获得。但是,这丢失了我要寻找的颜色变化。我该如何解决(获得正确的颜色变化以及正确的图例)?

1 个答案:

答案 0 :(得分:1)

通过更改标记的面部颜色和边缘颜色非常简单。这里color='green'首先适用于标记和线条。然后,您可以将标记边缘颜色(mec)和标记面颜色(mfc)更改为蓝色

fig, ax = plt.subplots()

plt.plot(x, y, '-o', color='green', mfc='b', 
         mec='b', markersize=6, label='blah')

ax.legend()
plt.show()

enter image description here