我是Python的新手,我用下面的代码在matplotlibseaborn中生成了一个boxplot(带有swarmplot叠加)。
我已经用下面的代码在matplotlibseaborn中生成了一个boxplot(有一个swarplot覆盖)。我现在想添加一个图例,它与每个方框的颜色方案一致。我在网上找到的许多解决方案似乎并不适用于这种特殊类型的图形 (例如,只适用与 分组曲线图).
当我试图实现建议的代码时 此处 我收到错误信息。
所有的投入都非常感激!
# Import libraries and modules
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Set seaborn style.
sns.set(style="whitegrid", palette="colorblind")
# Load summary tidy data.
tidy = pd.read_csv('tidy.csv')
# Define plots for tidy data
fig, ax = plt.subplots(figsize=(10,6))
ax = sns.boxplot(x='header1', y='header2', data=tidy, order=["header1", "header2"])
ax = sns.swarmplot(x="header1", y="header2", data=tidy, color=".25", order=["header1", "header2"])
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = 'header1'
labels[1] = 'header2'
ax.set_xticklabels(labels)
ax.legend(loc='best')
我正在处理的数据的例子。
Object,Metric,Length
MT1,B2A1,3.57675
MT1,B2A2,2.9474600000000004
MT1,B2A3,2.247772857142857
MT1,B2A4,3.754455
MT1,B2A5,2.716282
MT1,B2A6,2.91325
MT10,B2A1,3.34361
MT10,B2A2,2.889958333333333
MT10,B2A3,2.22087
MT10,B2A4,2.87669
MT10,B2A5,1.6745005555555557
MT12,B2A1,3.3938900000000003
MT12,B2A2,2.00601
MT12,B2A3,2.1720200000000003
MT12,B2A4,2.452923333333333
... no handles with labels found to put in the legend
错误是由于调用 ax.legend()
而你的两个艺术家(boxplot和swarmplot)没有标签。
sns.boxplot
是基于matplotlib的 曲线图 和 sns.swarmplot
关于 散射所以你只需要分别给他们一个 labels
和 label
争论。
ax = sns.boxplot(..., labels=["Metric", "Length"])
ax = sns.swarmplot(..., label="something goes here")
另外,根据 这个 你可以不动用海床部分,而去摆弄。
handles, _ = ax.get_legend_handles_labels() # Get the artists.
ax.legend(handles, ["label1", "label2"], loc="best") # Associate manually the artists to a label.