当我的数据来自 python 字典时,如何将类别名称添加到我的 seaborn 箱线图中?
How do I add category names to my seaborn boxplot when my data is from a python dictionary?
我有一些数据位于 python 列表字典中。
如何使用字典中的键作为此箱线图的类别标签?
这是字典的示例,plot_data:
plot_data {
'Group1': [0.02339976, 0.03235323, 0.12835462, 0.10238375, 0.04223188],
'Group2': [0.02339976, 0.03235323, 0.12835462, 0.10238375, 0.04223188]
}
这段代码可能是一团糟,但在这里:
data = plot_data.values()
#Get data in proper format
fixed_data = list(sorted(data))
#Set up the graph parameters
sns.set(context='notebook', style='whitegrid')
sns.axlabel(xlabel="Groups", ylabel="Y-Axis", fontsize=16)
#Plot the graph
sns.boxplot(data=fixed_data, whis=np.inf, width=.18)
sns.swarmplot(data=fixed_data, size=6, edgecolor="black", linewidth=.9)
这里是如何添加类别标签"manually":
import seaborn as sns, matplotlib.pyplot as plt, operator as op
plot_data = {
'Group1': range(10,16),
'Group2': range(5,15),
'Group3': range(1,5)
}
# sort keys and values together
sorted_keys, sorted_vals = zip(*sorted(plot_data.items(), key=op.itemgetter(1)))
# almost verbatim from question
sns.set(context='notebook', style='whitegrid')
sns.axlabel(xlabel="Groups", ylabel="Y-Axis", fontsize=16)
sns.boxplot(data=sorted_vals, width=.18)
sns.swarmplot(data=sorted_vals, size=6, edgecolor="black", linewidth=.9)
# category labels
plt.xticks(plt.xticks()[0], sorted_keys)
plt.show()
这里是输出:
我有一些数据位于 python 列表字典中。
如何使用字典中的键作为此箱线图的类别标签? 这是字典的示例,plot_data:
plot_data {
'Group1': [0.02339976, 0.03235323, 0.12835462, 0.10238375, 0.04223188],
'Group2': [0.02339976, 0.03235323, 0.12835462, 0.10238375, 0.04223188]
}
这段代码可能是一团糟,但在这里:
data = plot_data.values()
#Get data in proper format
fixed_data = list(sorted(data))
#Set up the graph parameters
sns.set(context='notebook', style='whitegrid')
sns.axlabel(xlabel="Groups", ylabel="Y-Axis", fontsize=16)
#Plot the graph
sns.boxplot(data=fixed_data, whis=np.inf, width=.18)
sns.swarmplot(data=fixed_data, size=6, edgecolor="black", linewidth=.9)
这里是如何添加类别标签"manually":
import seaborn as sns, matplotlib.pyplot as plt, operator as op
plot_data = {
'Group1': range(10,16),
'Group2': range(5,15),
'Group3': range(1,5)
}
# sort keys and values together
sorted_keys, sorted_vals = zip(*sorted(plot_data.items(), key=op.itemgetter(1)))
# almost verbatim from question
sns.set(context='notebook', style='whitegrid')
sns.axlabel(xlabel="Groups", ylabel="Y-Axis", fontsize=16)
sns.boxplot(data=sorted_vals, width=.18)
sns.swarmplot(data=sorted_vals, size=6, edgecolor="black", linewidth=.9)
# category labels
plt.xticks(plt.xticks()[0], sorted_keys)
plt.show()
这里是输出: