How to overlay two plots in same figure in plotly ( Create Pareto chart in plotly )?

后端 未结 3 863
耶瑟儿~
耶瑟儿~ 2021-02-14 19:01

I was trying to plot barplot and scatterplot in the same plot in plotly, but it shows only scatterplot.

How to show both the plots?

data

import         


        
3条回答
  •  梦毁少年i
    2021-02-14 19:49

    • matplotlib twinx() function can instantiate a second axes that shares the same x-axis.
    • plt.xticks(rotation=90) to rotate x axis label.
    • z-order to specify the drawing order.
    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame({
                'price': [ 4.0, 17.0, 7.0, 7.0, 2.0, 1.0, 1.0],
                'item': ['apple', 'banana', 'carrot', 'plum',
                        'orange', 'date', 'cherry']})
    
    num = 'price'
    cat = 'item'
    
    df = df.sort_values(num, ascending=False)
    df['cumulative_sum'] = df[num].cumsum()
    df['cumulative_perc'] = 100*df['cumulative_sum']/df[num].sum()
    
    df['demarcation'] = 80
    
    title = 'Pareto Chart'
    
    plt.figure(figsize=(9, 3))
    
    axes1 = plt.subplot()
    b = axes1.bar(df[cat], df[num], label='Price')
    
    plt.xticks(rotation=90)
    
    # use twinx() function to create the second axis object “ax2”
    axes2 = axes1.twinx()
    
    p = axes2.plot(df[cat], df['cumulative_perc'], c='r', marker='o', zorder=5, label='Cumulative Percentage')
    
    axes1.legend(handles=(b, p[0]), loc='center right')
    
    plt.tight_layout()
    plt.show()
    

提交回复
热议问题