[英]Python seaborn / matplotlib - show frequency in legend categories in sns.countplot()
[英]How to show all categories in legend in pie chart with matplotlib python
您好,我正在尝试 plot 图表,但在显示图例时遇到了一些困难。 下面是我的代码:
age = ['below 20', '20-30', '30-40', '40-50']
age_count = [23,0,35,0]
labels = age
sizes = age_count
fig1, ax1 = plt.subplots()
ax1.pie(sizes, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.legend(labels,bbox_to_anchor=(1, 0),loc='lower left')
我不想在饼图 plot 中显示计数为零的类别。我仍然想在图例中显示所有类别名称(即 20-30,40-50)。 我尝试了上面的代码,但它现在可以工作了。 想知道哪里出错了?
来自 matplotlib.pyplot.pie 文档:
"autopct None or str or callable, default: None
如果不是无,是一个字符串或 function 用于 label 楔形及其数值。 label 将被放置在楔形内。 如果它是格式字符串,则 label 将是 fmt % pct。 如果它是 function,它将被调用。”
您可以通过将 function 传递给 autopct 来指定特定的 bihavier,如下所示:
import matplotlib.pyplot as plt
age = ['below 20', '20-30', '30-40', '40-50']
age_count = [23,0,35,0]
def f(cpt):
if cpt == 0:
return ''
else:
return '%.2f' %cpt
fig1, ax1 = plt.subplots()
ax1.pie(age_count, autopct=f,
shadow=True, startangle=90)
ax1.legend(age,bbox_to_anchor=(1, 0),loc='lower left')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.