我有一个数据帧sales
的列[ book_name
,num_orders
,condition
,price
。
condition
有4个变体。对于每个book_name
,我只尝试绘制那些具有num_orders
> = 10的条件的条形图。
因此,我这样做:
sns.barplot(x='book_name', y='price', hue='condition', data=sales[sales.num_orders>=10])
现在,我想在其对应的条形图上显示num_orders
每种条件book_name
。如果由于阈值10而未绘制,则跳过它。
我该如何实现?
示例数据框:
import pandas as pd
sales = pd.DataFrame.from_dict({"book_name":["Island", "Island", "Island","Island", "Cinder","Cinder", "Cinder","Cinder","Speak","Speak","Speak","Speak"],
"num_orders" : [15, 17, 3,40,57,120,5,65,34,6,7,8],
"condition":["New", "Old", "Rough","Torn","New", "Old", "Rough","Torn","New", "Old", "Rough","Torn"],
"price":[700,600,500,400,1000,900,800,700,1500,1400,1300,1200]})
当我跑步时:
sns.barplot(x='book_name',y='price',data=sales,hue='condition')
sns.barplot(x='book_name',y='price',data=sales[sales.num_orders>10],hue='condition')
我想在绘制的条形图上显示num_orders的值。如果没有酒吧,那就没有价值。欢迎使用其他库的建议,但也请针对我正在使用hue并希望在这些栏上方显示其他某些列的值的解决方案发布此特定问题。
我通过尝试以下方法得到了解决方案:
def display_figures(ax,df):
show=df.num_orders.to_list()
i=0
for p in ax.patches:
h=p.get_height()
if (h>0):
value=show[i]
ax.text(p.get_x()+p.get_width()/2,h+10, value, ha='center')
i=i+1
plt.figure(figsize=(15,10))
plot_data=sales[sales.num_orders>=10].sort_values(by='cond_id')
ax=sns.barplot(x='book_name',y='price',data=plot_data, hue='condition')
display_figures(ax,plot_data)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句