[英]matplotlib: match legend text color with symbol in scatter plot
我制作了一個有3種不同顏色的散點圖,我希望匹配符號的顏色和圖例中的文字。
對於線圖的情況,存在一個很好的解決方案 :
leg = ax.legend()
# change the font colors to match the line colors:
for line,text in zip(leg.get_lines(), leg.get_texts()):
text.set_color(line.get_color())
但是, get_lines()
無法訪問散點圖顏色。對於3種顏色的情況,我認為我可以使用例如逐個手動設置文本顏色。 text.set_color('r')
。 但我很好奇它是否能像線條一樣自動完成。 謝謝!
散點圖具有面色和邊緣顏色。 分散的圖例處理程序是PathCollection
。
因此,您可以遍歷圖例句柄並將文本顏色設置為圖例句柄的面部顏色
for h, t in zip(leg.legendHandles, leg.get_texts()):
t.set_color(h.get_facecolor()[0])
完整代碼:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
for i in range(3):
x,y = np.random.rand(2, 20)
ax.scatter(x, y, label="Label {}".format(i))
leg = ax.legend()
for h, t in zip(leg.legendHandles, leg.get_texts()):
t.set_color(h.get_facecolor()[0])
plt.show()
這似乎很復雜但確實能滿足您的需求。 歡迎提出建議。 我使用ax.get_legend_handles_labels()
來獲取標記並使用tuple(handle.get_facecolor()[0])
來獲取matplotlib顏色元組。 用這樣一個非常簡單的散點圖做了一個例子:
由於重要性,鮑勃·歐內斯特在他的回答中指出:
leg.legendHandles
將返回圖例句柄; 代碼簡化為:
import matplotlib.pyplot as plt
from numpy.random import rand
fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
x, y = rand(2, 10)
ax.scatter(x, y, c=color, label=color)
leg = ax.legend()
for handle, text in zip(leg.legendHandles, leg.get_texts()):
text.set_color(handle.get_facecolor()[0])
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.