【问题标题】:Combination Chart Problem in Displaying Xlabel and its Correct Quantity?显示 Xlabel 及其正确数量时的组合图问题?
【发布时间】:2021-03-22 02:22:08
【问题描述】:
StockCode Quantity Revenue
22326 1248 3643.20
15036 1164 853.32
POST 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()

【问题讨论】:

  • 1) 不要将数据作为图像发布。我们应该手动输入吗? 2)在您的代码中,您有很多未定义的变量和未导入的模块
  • @PaulH 很抱歉给您带来不便。我已经更新了更多信息。谢谢!

标签: python matplotlib seaborn combinations visualization


【解决方案1】:

你得到这个是因为 lineplot 和 barplot 对 x 变量的排序不同。您可以简单地将您的 StockCode 转换为类别:

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

运行你的代码,你应该得到:

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多