Warm tip: This article is reproduced from serverfault.com, please click

python-显示Xlabel及其正确数量时的组合图问题?

(python - Combination Chart Problem in Displaying Xlabel and its Correct Quantity?)

发布于 2020-12-10 16:17:40
股份代号 数量 收入
22326 1248 3643.20
15036 1164 853.32
邮政 1124 21181.00
20719 1021 854.85
21212 1002 551.10
22585 936 1033.20
22423 881 9866.55
22629 877 1633.35
22554 872 1438.80
22961 818 1186.10

我有一个df_ger_top10这样的表,我想可视化一个组合图,包括每个股票代码的收入和数量。但是,当我在图表中可视化它们时,条形图显示的数量是错误的,我也不知道为什么。似乎在添加收入线时修改了xlabel,因为当我删除收入线图时,它变得很正常。这是我的组合图代码,其中显示了每种股票代码的数量错误。

import numpy as np
import pandas as pd
import seaborn as sns
import plotly.express as px
import matplotlib.pyplot as plt
%matplotlib inline 

fig, ax1 = plt.subplots(figsize=(15,8))

ax2 = ax1.twinx()
sns.barplot(x= df_ger_top10.StockCode,
            y= df_ger_top10.Quantity, 
            color='#004488',
            ax=ax1)
for p in ax1.patches: 
    height =p.get_height()
    ax1.text(p.get_x()+p.get_width()/2.,
        height + 3,
        '{:1.0f}'.format(height),
        ha="center", fontsize=12)
ax1.set_title('Top Selling Categories and Revenue',weight='bold',fontsize=16)
ax1.set_ylabel('Quantity',weight='bold',fontsize=13)
ax1.set_xlabel('Stock Code', weight='bold',fontsize=13)


sns.lineplot(x=df_ger_top10.StockCode, 
             y=df_ger_top10.Revenue,
             color='g',
             marker="o",
             ax=ax2)
ax2.set_ylabel('Revenue',weight='bold',fontsize=13)

ymin, ymax = ax2.get_ylim()
bonus = (ymax - ymin)/40
for x, y, name in zip(df_ger_top10['StockCode'], round(df_ger_top10['Revenue']), round(df_ger_top10['Revenue']).astype('str').replace('\.0', '', regex=True)):
    ax2.text(x, y + bonus, name, color = 'g', weight = 'bold', ha='right')
plt.show()

我的可视化

Questioner
Hải Chi Nguyễn Phạm
Viewed
11
StupidWolf 2020-12-11 14:38:19

之所以会这样,是因为线图和条形图对x变量的排序不同。你可以简单地将StockCode转换为以下类别:

df_ger_top10.StockCode = pd.Categorical(df_ger_top10.StockCode)

并运行你的代码,你应该获得:

在此处输入图片说明