how to combine two bar chart of two files in one diagram in matplotlib pandas

前端 未结 1 1131
别跟我提以往
别跟我提以往 2021-01-25 01:44

I have two dataframe with the same columns but different content. I have plotted dffinal data frame. now I want to plot another dataframe dffinal_no on

相关标签:
1条回答
  • 2021-01-25 02:12

    to compare two data frame result with bar plot one way you could try is concatenating two data frames and adding hue. For example consider below df it contains same x and y columns in both df's and wanna compare this values. to achieve this simply add hue column for each df with differentiating constant like below.

    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    df1=pd.DataFrame({'x':[1,2,3,4,5],'y':[10,2,454,121,34]})
    df2=pd.DataFrame({'x':[4,1,2,5,3],'y':[54,12,65,12,8]})
    df1['hue']=1
    df2['hue']=2
    res=pd.concat([df1,df2])
    sns.barplot(x='x',y='y',data=res,hue='hue')
    plt.show()
    

    The result should looks like below:

    To get two y-axis try this method,

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()
    
    ax1.set_ylabel('final-formula')
    ax2.set_ylabel('numPatients6month')
    
    width=0.4
    
    df1=df1.set_index('x').sort_index()
    df2=df2.set_index('x').sort_index()
    
    df1['y'].plot(kind='bar',color='blue',ax=ax1,width=width,position=1)
    df2['y'].plot(kind='bar',color='green',ax=ax2,width=width,position=0)
    plt.show()
    

    with actual input:

    fig = plt.figure()
    
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()
    
    ax1.set_ylabel('final-formula')
    ax2.set_ylabel('numPatients6month')
    
    
    width=0.4
    
    df1=df1.set_index('6month').sort_index()
    df2=df2.set_index('6month').sort_index()
    
    df1['final-formula'].plot(kind='bar',color='blue',ax=ax1,width=width,position=1)
    df2['numPatients6month'].plot(kind='bar',color='green',ax=ax2,width=width,position=0)
    plt.show()
    

    0 讨论(0)
提交回复
热议问题