我正在尝试将图例项的颜色更改为黑色。过去我用scatter
而不是plot
做过类似的事情,但是因为我也想要fillstyle
,所以我需要使用plot
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import container
def ColorExtractor(cmap, colist):
cmap = matplotlib.cm.get_cmap(cmap)
rbga = cmap(colist)
return rbga
colors = ColorExtractor('Blues', [3/3, 3/3, 2/3, 1/3])
fig, ax = plt.subplots()
x_data = np.array([0.975, 0.75, 0.525])
y_min = np.array([3, 3, 2])
y_max = np.array([4, 4, 3])
for xs, ys, cols, labs, flstl in zip([x_data, x_data], [y_min, y_max], [colors, colors], ['$x_{min}$', '$x_{max}$'], ['bottom', 'top']):
ax.plot(xs, ys, 'k:')
for x, y, col in zip(xs, ys, cols):
ax.plot(x, y, color=col, marker='<', label=labs, fillstyle=flstl, markeredgecolor='k', linestyle='none', markersize=10)
ax.set_xlim(0.5, 1)
ax.set_ylim(1, 5)
ax.set_xlabel('$x$', fontsize=15)
ax.set_ylabel('$y$', fontsize=15)
handles, labels = ax.get_legend_handles_labels()
handles = [i[0] if isinstance(i, container.ErrorbarContainer) else i for i in handles]
by_label = dict(zip(labels, handles))
ax.legend(by_label.values(), by_label.keys(), loc=9, ncol=2, frameon=False)
leg = ax.get_legend()
for i in leg.legendHandles:
i.set_color('k')
i.set_markeredgecolor('k')
#i.set_edgecolor('k')
plt.show()
除了最后一部分似乎什么也没做之外,一切都很好。因此,图例符号的颜色保持为蓝色而不是黑色。我还希望edgecolor
是黑色的,但我已经对它进行了注释,因为AttributeError: 'Line2D' object has no attribute 'set_edgecolor'
会生成
编辑:正如@Galunid指出的,我可能应该使用set_markeredgecolor
而不是set_edgecolor
。但是,主要问题是我想将图例标记内的颜色更改为黑色
我做错了什么
如果过早更改图例控制柄,绘图内的颜色也将更改。因此,您需要复制句柄,然后为这些副本上色。注意
set_markerfacecolor()
更改标记的第一种颜色(blue
在示例代码中)。并且set_markerfacecoloralt()
会改变第二种颜色(即white
)。因此,您可能需要set_markerfacecolor('black')
并保持其他颜色不变以下是一个例子:
相关问题 更多 >
编程相关推荐