向 seaborn 箱线图添加自定义图例
Add custom legend to seaborn boxplots
我用seaborn生成了M个方法的N个箱线图,然后我用相同的颜色给每个方法的箱线图上色。我现在只想添加一个图例,以不同颜色显示 M 方法的名称(例如 red_line 方法 A、blue_line 方法 B 等等)。任何快速的方法来做到这一点?
bplot = sns.boxplot(data=[d for d in data])
colors = ["red", "green", "blue"]
color_counter = 0
for i in range(len(data)-len(c)):
mybox = bplot.artists[i]
mybox.set_facecolor(colors[color_counter])
color_counter = color_counter + 1
if color_counter == len(methods):
color_counter=0
# COMMENTING NEXT CODE BLOCK AS IT OUTPUTS TEXT ASSOCIATED TO GRAY LINES (I want them to be colored instead)
# leg = plt.legend(labels=[method for method in methods])
# for legobj in leg.legendHandles:
# legobj.set_linewidth(12.0)
# params = {'legend.fontsize': 80}
# plt.rcParams.update(params)
plt.legend()
plt.title('Title')
plt.show()
Matplotlib 允许您创建自定义图例,其中几乎包含您想要的任何内容。
见https://matplotlib.org/3.2.1/gallery/text_labels_and_annotations/custom_legends.html
对于你的情况,你会创建类似
的东西
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
legend_elements = [Line2D([0], [0], color='red', lw=4, label='Method 1'),
Line2D([0], [0], color='green', lw=4, label='Method 2'),
Line2D([0], [0], color='blue', lw=4, label='Method 3')]
# Create the figure
fig, ax = plt.subplots()
ax.legend(handles=legend_elements, loc='center')
plt.show()
我用seaborn生成了M个方法的N个箱线图,然后我用相同的颜色给每个方法的箱线图上色。我现在只想添加一个图例,以不同颜色显示 M 方法的名称(例如 red_line 方法 A、blue_line 方法 B 等等)。任何快速的方法来做到这一点?
bplot = sns.boxplot(data=[d for d in data])
colors = ["red", "green", "blue"]
color_counter = 0
for i in range(len(data)-len(c)):
mybox = bplot.artists[i]
mybox.set_facecolor(colors[color_counter])
color_counter = color_counter + 1
if color_counter == len(methods):
color_counter=0
# COMMENTING NEXT CODE BLOCK AS IT OUTPUTS TEXT ASSOCIATED TO GRAY LINES (I want them to be colored instead)
# leg = plt.legend(labels=[method for method in methods])
# for legobj in leg.legendHandles:
# legobj.set_linewidth(12.0)
# params = {'legend.fontsize': 80}
# plt.rcParams.update(params)
plt.legend()
plt.title('Title')
plt.show()
Matplotlib 允许您创建自定义图例,其中几乎包含您想要的任何内容。
见https://matplotlib.org/3.2.1/gallery/text_labels_and_annotations/custom_legends.html
对于你的情况,你会创建类似
的东西from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
legend_elements = [Line2D([0], [0], color='red', lw=4, label='Method 1'),
Line2D([0], [0], color='green', lw=4, label='Method 2'),
Line2D([0], [0], color='blue', lw=4, label='Method 3')]
# Create the figure
fig, ax = plt.subplots()
ax.legend(handles=legend_elements, loc='center')
plt.show()