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

Combination Chart Problem in Displaying Xlabel and its Correct Quantity?

发布于 2020-12-10 16:17:40
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

I have a table called df_ger_top10 like this and I want to visualize a combination chart including revenue and quantity of each stock code. However, when I visualize them in a chart, the quantity shown for bar chart is wrong, and I don't know why. It seems like the xlabel is modified when I add revenue line because when I remove the line graph of revenue, it becomes normal. Here is my code for the combination chart, which shows wrong quantity of each stock code.

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()

My visualization

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

You get this because the lineplot and barplot order your x variables differently. You can simply convert your StockCode to category:

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

And run your code, and you should get:

enter image description here