【问题标题】:How to overlay two plots in same figure in plotly ( Create Pareto chart in plotly )?如何在 plotly 中覆盖同一图中的两个图(在 plotly 中创建帕累托图)?
【发布时间】:2020-09-28 21:21:53
【问题描述】:

我试图在同一图中绘制条形图和散点图,但它只显示散点图。

如何显示两个图?

数据

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter

import plotly
import plotly.offline as py
import plotly.graph_objs as go
import plotly.figure_factory as ff
import plotly.tools as tls
from plotly.subplots import make_subplots
from plotly.offline import plot, iplot, init_notebook_mode
init_notebook_mode(connected=False)

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']})

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


num = 'price'
cat = 'item'
title = 'Pareto Chart'

代码

trace1 = go.Bar(
    x=df[cat],
    y=df[num],
    name=num,
    marker=dict(
        color='rgb(34,163,192)'
               )
)
trace2 = go.Scatter(
    x=df[cat],
    y=df['cumulative_perc'],
    name='Cumulative Percentage',
    yaxis='y2',

)

data = [trace1,trace2]

fig = dict(data=data)
iplot(fig)

输出

必填

  • 同时显示条形图和散点图
  • 左侧 y 轴上的条形图 y 刻度
  • 右侧 y 轴上的散点图 y 刻度
  • xticklabels 旋转 90 度

【问题讨论】:

标签: python plotly


【解决方案1】:

试试这个:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

trace1 = go.Bar(
    x=df[cat],
    y=df[num],
    name=num,
    marker=dict(
        color='rgb(34,163,192)'
               )
)
trace2 = go.Scatter(
    x=df[cat],
    y=df['cumulative_perc'],
    name='Cumulative Percentage',
    yaxis='y2'

)

fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(trace1)
fig.add_trace(trace2,secondary_y=True)
fig['layout'].update(height = 600, width = 800, title = title,xaxis=dict(
      tickangle=-90
    ))
iplot(fig)

给,

【讨论】:

【解决方案2】:

你可以这样做:

fig = make_subplots(rows=1, cols=2)
fig.add_trace(trace1, row=1, col=1)
fig.add_trace(trace2, row=1, col=2)

fig.update_layout(xaxis=dict(tickangle=90))
fig.show()

这将产生以下图表:

【讨论】:

    【解决方案3】:
    • matplotlib twinx() 函数可以实例化第二个轴,共享相同的 x 轴。
    • plt.xticks(rotation=90) 旋转 x 轴标签。
    • z-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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-16
      • 2020-01-19
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 2021-12-06
      相关资源
      最近更新 更多