[英]Why is my legend in my seaborn countplot not showing all the labels?
I have a Seaborn countplot showing seven different animal classes:我有一个 Seaborn 计数图,显示七种不同的动物类别:
g = sns.countplot(data=df, x="class_type")
plt.legend(title="Animal Type", loc="upper right", labels=["Mammal", "Bird", "Reptile", "Fish",
"Amphibian", "Bug", "Invertebrate"])
plt.show(g)
which gives me this image.这给了我这个形象。
as you can see, only the first label is displayed.如您所见,仅显示第一个 label。 How do I show the label for each bar, please?
请问如何显示每个条的 label?
this is the top (first 20 rows) of my dataframe:这是我的 dataframe 的顶部(前 20 行):
animal_name hair feathers eggs milk airborne aquatic predator \
0 aardvark 1 0 0 1 0 0 1
1 antelope 1 0 0 1 0 0 0
2 bass 0 0 1 0 0 1 1
3 bear 1 0 0 1 0 0 1
4 boar 1 0 0 1 0 0 1
5 buffalo 1 0 0 1 0 0 0
6 calf 1 0 0 1 0 0 0
7 carp 0 0 1 0 0 1 0
8 catfish 0 0 1 0 0 1 1
9 cavy 1 0 0 1 0 0 0
10 cheetah 1 0 0 1 0 0 1
11 chicken 0 1 1 0 1 0 0
12 chub 0 0 1 0 0 1 1
13 clam 0 0 1 0 0 0 1
14 crab 0 0 1 0 0 1 1
15 crayfish 0 0 1 0 0 1 1
16 crow 0 1 1 0 1 0 1
17 deer 1 0 0 1 0 0 0
18 dogfish 0 0 1 0 0 1 1
19 dolphin 0 0 0 1 0 1 1
toothed backbone breathes venomous fins legs tail domestic \
0 1 1 1 0 0 4 0 0
1 1 1 1 0 0 4 1 0
2 1 1 0 0 1 0 1 0
3 1 1 1 0 0 4 0 0
4 1 1 1 0 0 4 1 0
5 1 1 1 0 0 4 1 0
6 1 1 1 0 0 4 1 1
7 1 1 0 0 1 0 1 1
8 1 1 0 0 1 0 1 0
9 1 1 1 0 0 4 0 1
10 1 1 1 0 0 4 1 0
11 0 1 1 0 0 2 1 1
12 1 1 0 0 1 0 1 0
13 0 0 0 0 0 0 0 0
14 0 0 0 0 0 4 0 0
15 0 0 0 0 0 6 0 0
16 0 1 1 0 0 2 1 0
17 1 1 1 0 0 4 1 0
18 1 1 0 0 1 0 1 0
19 1 1 1 0 1 0 1 0
catsize class_type
0 1 1
1 1 1
2 0 4
3 1 1
4 1 1
5 1 1
6 1 1
7 0 4
8 0 4
9 0 1
10 1 1
11 0 2
12 0 4
13 0 7
14 0 7
15 0 7
16 0 2
17 1 1
18 1 4
19 1 1
as you can see, it's a mix of numeric, string and one hot encoded data.如您所见,它是数字、字符串和一个热编码数据的混合体。
Thank you for including the sample data.感谢您提供示例数据。
One issue seems to be that the plt.legend()
command isn't operating on your current axis.一个问题似乎是
plt.legend()
命令不在您当前的轴上运行。
You can do this instead:你可以这样做:
import seaborn as sns, pandas as pd, matplotlib.pyplot as plt
ax = sns.countplot(data=df, x="class_type", hue='class_type', dodge=False)
h,l = ax.get_legend_handles_labels()
labels=["Mammal", "Bird", "Reptile", "Fish", "Amphibian", "Bug", "Invertebrate"]
ax.legend(h,labels,title="Animal Type", loc="upper right")
plt.show()
The dodge=False
kwarg tip was found here: https://github.com/mwaskom/seaborn/issues/871 dodge=False
kwarg 提示在这里找到: https://github.com/mwaskom/seaborn/issues/871
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.