Home > database >  sorting in linechart along with bar chart in seaborn
sorting in linechart along with bar chart in seaborn

Time:11-02

I have a dataframe

    A   B           C
3   4   0.425744    62244
2   3   0.351339    61479
1   2   0.221772    62677
0   1   0.204175    63181

using field C for barplot and B in lineplot,

#code of plot 
fig, ax1 = plt.subplots(1,1,figsize=(6,4))
sns.lineplot(data = af['B'], marker='o', ax=ax1,)
ax2 = ax1.twinx()
sns.barplot(data = af, x='A',y="C" , alpha=0.5, ax=ax2)

enter image description here

I want to sort the value according to the line charts. In our case the sequence should be 4-3-2-1.

CodePudding user response:

If I understand correctly:

  1. Convert A to str:

    af['A'] = af['A'].astype(str)
    
  2. Instead of data=af['B'], use af as the data source with x='A':

    sns.lineplot(data=af, x='A', y='B', marker='o', ax=ax1)
    

Code and output:

af['A'] = af['A'].astype(str)

fig, ax1 = plt.subplots(1,1,figsize=(6,4))
sns.lineplot(data=af, x='A', y='B', marker='o', ax=ax1)
ax2 = ax1.twinx()
sns.barplot(data=af, x='A', y='C', alpha=0.5, ax=ax2)

  • Related