首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Matplotlib Xticks混淆

Matplotlib Xticks混淆
EN

Stack Overflow用户
提问于 2020-05-18 20:20:40
回答 1查看 55关注 0票数 0

我想使用matplotlib为两个目标组创建一个条形图:销售'1‘,而不是销售'0’。我的数据:

代码语言:javascript
复制
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

当前代码:

代码语言:javascript
复制
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)

问题:在图形xticks中,销售量为'0‘的项目为1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0与销售量为'1’的项目编号1.0,3.0,4.0,5.0,6.0,7.0,8.0不匹配。

代码语言:javascript
复制
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项分开

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-19 07:48:00

这种柱状图很容易用Seaborn绘制。hue关键字根据给定列分配颜色,并创建“隐藏”条。

代码语言:javascript
复制
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

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(f'{height:.0f}',
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

df = pd.DataFrame({'Sale': [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1],
                   'item': [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],
                   'Count': [3520, 9, 2095, 586, 609, 427, 101, 111, 88, 43, 28, 36, 16, 3, 4]})

ax = sns.barplot(x='item', y='Count', hue='Sale', data=df)
ax.set_ylabel('Count')
ax.set_title('Sale by Traffice Source')
autolabel(ax.containers[0])
autolabel(ax.containers[1])
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, ['No sale', 'Sale'])
plt.show()

PS:默认图例将“销售”(hue='Sale')列的值放入图例中。当前为0和1。要自动在图例中包含所需的字符串,可以将列值重命名为:df['Sale'] = np.where(df['Sale'] == 0, 'No sale', 'Sale')

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61869463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档