Python Matplotlib Xticks混淆
我想使用matplotlib为两个目标组创建条形图:销售“1”和非销售“0”。我的数据:Python Matplotlib Xticks混淆,python,matplotlib,seaborn,Python,Matplotlib,Seaborn,我想使用matplotlib为两个目标组创建条形图:销售“1”和非销售“0”。我的数据: Sale item Count 0 1.0 3520 2.0 9 3.0 2095 4.0 586 5.0
Sale item Count
0 1.0 3520
2.0 9
3.0 2095
4.0 586
5.0 609
6.0 427
7.0 101
8.0 111
1 1.0 88
3.0 43
4.0 28
5.0 36
6.0 16
7.0 3
8.0 4
当前代码:
fig, ax = plt.subplots(figsize=(10,4))
labels=['1.0','2.0','3.0','4.0', '5.0', '6.0', '7.0', '8.0']
itemSale0 = X_train[X_train.hasSale==0]
itemSale0=itemSale0.groupby('item').size().values
x = np.arange(len(labels)) # the label locations
width = 0.35 # the width of the bars
rects1=ax.bar(x - width/2, itemSale0, width, label='Not Sale')
labels=['1.0','3.0','4.0', '5.0', '6.0', '7.0', '8.0']
itemSale1 = X_train[X_train.hasSale==1]
itemSale1 = itemSale1.groupby('item').size().values
x = np.arange(len(labels)) # the label locations
width = 0.35 # the width of the bars
rects2=ax.bar(x + width/2, itemSale1, width, label='Sale')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Count')
ax.set_title('Sale by Traffice Source')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
问题:销售为“0”的物料编号为1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0与销售为“1”的物料编号在图形xticks中为1.0,3.0,4.0,5.0,6.0,7.0,8.0不匹配
items where sale is not are 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0
items where sale are 1.0, ,3.0,4.0,5.0,6.0,7.0,8.0
两者重叠请参见附件屏幕,它无法区分项目2.0中9项未售出,其栏已合并到xticks项目3中43项已售出,如何显示xticks,它可以将项目2.0中的9项未售出和项目3.0中的43项售出分开
这种条形图很容易用Seaborn绘制。色调关键字根据给定列指定颜色,并创建减淡条 将numpy作为np导入 将matplotlib.pyplot作为plt导入 作为pd进口熊猫 导入seaborn作为sns def autolabelrects: 在*rects*中的每个条上方附加一个文本标签,显示其高度。 对于矩形中的矩形: 高度=rect.get\u高度 ax.annotatef'{height:.0f}', xy=rect.get\u x+rect.get\u宽度/2,高度, xytext=0,3,3点垂直偏移 textcoords=偏移点, ha='中间',va='底部' 数据帧{'Sale':[0,0,0,0,0,0,0,0,1,1,1,1,1], “项目”:[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,1.0,3.0,4.0,5.0,6.0,7.0,8.0], “计数”:[3520、92095、586、609、427、101、111、88、43、28、36、16、3、4]} ax=sns.barplotx='item',y='Count',hue='Sale',data=df ax.set_ylabel'Count' ax.设置标题“按流量来源销售” autolabelax.containers[0] autolabelax.containers[1] 句柄,标签=ax.get\u图例\u句柄\u标签 ax.legendhandles,['No sale','sale'] 节目
PS:默认图例将“Sale”hue='Sale'列的值放入图例中。它们当前是0和1。要在图例中自动包含所需字符串,可以重命名列值:df['Sale']=np。其中df['Sale']==0,'No Sale','Sale'。我对matplotlib和seaborn很幼稚,因此这意味着seaborn比使用matplotlib更灵活,对吗?seaborn比纯matplotlib做很多事情更自动化。如果需要特殊功能,例如自动标记,可以通过matplotlib调整绘图。请看Seaborn's,了解使用少量代码可以实现的功能。matplotlib也可以实现这一点,但需要更多的编程。