使用补丁自定义散点图中的图例标记面色 [英] Customize legend marker facecolor in scatterplot with patches
问题描述
我有一个散点图,其中也包含一个椭圆.但是,图例仅包含Ellipse中的格式.我还如何反映散点图的格式?
在下面的示例中,我希望像在散点图中一样填充图例标记.
x = np.random.randn(60)y = np.random.randn(60)fig,ax = plt.subplots()sb.scatterplot(x,y,color ='red',ax = ax)椭圆= matplotlib.patches.Ellipse(xy =(0,0),宽度= 2,高度= 3,角度= 45,edgecolor ='红色',facecolor ='none')ax.add_patch(椭圆)ax.legend(['A'])plt.show()
Matplotlib的标准方法是为每个出现在图例中的项目分配一个标签.仅在标准方式无法提供所需结果的情况下,图例可以是
I have a scatter plot that also contains an ellipse. However, the legend only contains the formatting from the Ellipse. How can I also reflect the formatting from the scatter plot?
In the example below, I'd like the legend markers to be filled just like in the scatter plot.
x = np.random.randn(60)
y = np.random.randn(60)
fig,ax=plt.subplots()
sb.scatterplot(x, y,color='red', ax=ax)
ellipse = matplotlib.patches.Ellipse(
xy=(0, 0), width=2, height=3, angle=45,
edgecolor='red', facecolor='none'
)
ax.add_patch(ellipse)
ax.legend(['A'])
plt.show()
Matplotlib's standard way is to assign a label to each item to appear in the legend. Only in case the standard way wouldn't give the desired result, the legend can be customized.
Calling ax.legend()
without parameters creates the default legend. Customized handles can be created with Patch' and
Line2D` as in the code below.
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import numpy as np
import seaborn as sns
x = np.random.randn(60)
y = np.random.randn(60)
fig, ax = plt.subplots()
sns.scatterplot(x, y, color='red', ax=ax, label='scatter dots')
ellipse = Ellipse(xy=(0, 0), width=2, height=3, angle=45,
edgecolor='red', facecolor='none', label='ellipse')
ax.add_patch(ellipse)
handles, labels = ax.get_legend_handles_labels()
new_handles = [Patch(facecolor='white', edgecolor='red', hatch='ooo'),
Line2D([0], [0], marker='o', markerfacecolor='red', markeredgecolor='black', markersize=10, ls='')]
ax.legend(new_handles, labels)
plt.show()
这篇关于使用补丁自定义散点图中的图例标记面色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!