【问题标题】:How to save IPython Display如何保存 IPython 显示
【发布时间】:2021-01-29 13:29:54
【问题描述】:

我正在使用这个例子来生成我的图 Create dropdown button to filter based on a categorical column

如何将此显示保存为 HTML。我需要发送交互式图表。

编辑:

这是我的代码的样子:

from plotly import graph_objs as go
import ipywidgets as w
from IPython.display import display
import pandas as pd


x  = 'date'
y1 = 'price'
y2 = 'SHB Car price'

trace1 = {
    'x':final_df2[x],
    'y': final_df2[y1],
    'type': 'scatter',
    'mode': 'lines',
    'name':'price',
    'marker': {'color': 'blue'}
}

trace2={
    'x': final_df2[x],
    'y': final_df2[y2],
    'type': 'scatter',
    'mode': 'lines',
    'name':'SHB Car price',
    'marker': {'color': 'yellow'}
}

data = [trace1, trace2]

# Create layout for the plot
layout=dict(
    title='Analysis',
    xaxis=dict(
        title='Date', 
        type='date', 
        tickformat='%Y-%m-%d', 
        ticklen=5, 
        titlefont=dict(
            family='Old Standard TT, serif',
            size=20,
            color='black'
        )
    ),
    yaxis=dict(
        title='price', 
        ticklen=5,
        titlefont=dict(
            family='Old Standard TT, serif',
            size=20,
            color='black'
            )
        )

    )

# Here's the new part

fig = go.FigureWidget(data=data, layout=layout)

def update_fig(change):
    aux_df = final_df2[final_df2.brand.isin(change['new'])]
    with fig.batch_update():
        for trace, column in zip(fig.data, [y1, y2]):
            trace.x = aux_df[x]
            trace.y = aux_df[column]

drop = w.Dropdown(options=[
    ('All', ['bmw', 'ford','hyundai','mercedes-benz','nissan','opel','toyota','vw','audi', 'dacia', 'fiat', 'honda', 'kia', 'renault',
       'volvo']),
    ('bmw', ['bmw']),
    ('ford', ['ford']),
    ('hyundai', ['hyundai']),
    ('mercedes-benz', ['mercedes - benz']),
    ('nissan', ['nissan']),
    ('opel', ['opel']),
    ('toyota', ['toyota']),
    ('volkswagen', ['volkswagen']),
    ('audi', ['audi']),
    ('dacia', ['dacia']),
    ('fiat', ['fiat']),
    ('honda', ['honda']),
    ('kia', ['kia']),
    ('renault', ['renault']),
    ('volvo', ['volvo'])

])
drop.observe(update_fig, names='value')

display(w.VBox([drop, fig]))

这是我要显示的数据框:

我在这里发布 5 个值:

{'date': {0: Timestamp('2020-03-29 00:00:00'),
  1: Timestamp('2020-03-31 00:00:00'),
  2: Timestamp('2020-04-03 00:00:00'),
  3: Timestamp('2020-04-04 00:00:00'),
  4: Timestamp('2020-04-09 00:00:00')},
 'SHB Car price': {0: 137750.0,
  1: 62500.0,
  2: 32000.0,
  3: 43000.0,
  4: 66500.0},
 'brand': {0: 'volkswagen',
  1: 'citro�n',
  2: 'daewoo',
  3: 'citro�n',
  4: 'saab'},
 'str_id': {0: 'volkswagen_passat_2014_sedan_2012_2014_5_1598_105_front-wheel drive_semi-automatic_1.6 tdi bluemotion comfortline',
  1: 'citro�n_c5_2008_sedan____1560_110_front-wheel drive_manual_1.6 hdi sx',
  2: 'daewoo_nexia_2008_sedan____1450_63_front-wheel drive_manual_1.5 glx',
  3: 'citro�n_c5_2008_sedan____1560_110_front-wheel drive_manual_1.6 hdi sx',
  4: 'saab_9-3_2005_sedan____1900_138_front-wheel drive_automatic_1.9 tid vector'},
 'price': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
 'category': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan}}

这是图表的样子:

【问题讨论】:

    标签: python pandas plotly


    【解决方案1】:

    请按照下面的示例使用 plotly 下拉对象生成 plotly 散点图。 write.html 以前对你不起作用,因为它是 IPython 小部件的一部分,而不是情节的一部分。

    from plotly import graph_objs as go
    import pandas as pd
    import numpy as np
    
    final_df2 = pd.DataFrame(
    {'date': {0: pd.Timestamp('2020-03-29 00:00:00'),
      1: pd.Timestamp('2020-03-31 00:00:00'),
      2: pd.Timestamp('2020-04-03 00:00:00'),
      3: pd.Timestamp('2020-04-04 00:00:00'),
      4: pd.Timestamp('2020-04-09 00:00:00')},
     'SHB Car price': {0: 137750.0,
      1: 62500.0,
      2: 32000.0,
      3: 43000.0,
      4: 66500.0},
     'brand': {0: 'volkswagen',
      1: 'citro�n',
      2: 'daewoo',
      3: 'citro�n',
      4: 'saab'},
     'str_id': {0: 'volkswagen_passat_2014_sedan_2012_2014_5_1598_105_front-wheel drive_semi-automatic_1.6 tdi bluemotion comfortline',
      1: 'citro�n_c5_2008_sedan____1560_110_front-wheel drive_manual_1.6 hdi sx',
      2: 'daewoo_nexia_2008_sedan____1450_63_front-wheel drive_manual_1.5 glx',
      3: 'citro�n_c5_2008_sedan____1560_110_front-wheel drive_manual_1.6 hdi sx',
      4: 'saab_9-3_2005_sedan____1900_138_front-wheel drive_automatic_1.9 tid vector'},
     'price': {0: np.nan, 1: np.nan, 2: np.nan, 3: np.nan, 4: np.nan},
     'category': {0: np.nan, 1: np.nan, 2: np.nan, 3: np.nan, 4: np.nan}}
    )
    
    x  = 'date'
    y1 = 'price'
    y2 = 'SHB Car price'
    
    fig = go.Figure()
    
    brands = final_df2.brand.unique()
    brands.sort()
    
    for type in brands:
        df_temp = final_df2.query(f'brand== "{type}"')[y2]
        
        fig.add_trace(
            go.Scatter(
                x = df_temp.index,
                y = df_temp.values,
                name = type
            )
        )
    
    fig.update_layout(
        updatemenus=[go.layout.Updatemenu(
            buttons=list(
                [dict(label = 'All',
                      method = 'update',
                      args = [{'visible': [True, True, True, True]},
                              {'showlegend':True}]),
                 dict(label = 'Citreon',
                      method = 'update',
                      args = [{'visible': [True, False, False, False]}, # the index of True aligns with the indices of plot traces
                              {'showlegend':True}]),
                 dict(label = 'Daewoo',
                      method = 'update',
                      args = [{'visible': [False, True, False, False]},
                              {'showlegend':True}]),
                 dict(label = 'Saab',
                      method = 'update',
                      args = [{'visible': [False, False, True, False]},
                              {'showlegend':True}]),
                 dict(label = 'Volkswagon',
                      method = 'update',
                      args = [{'visible': [False, False, False, True]},
                              {'showlegend':True}]),
                ]),
            x=0.23,
            y=1.10
            )])
    
    
    # Add annotation
    fig.update_layout(
        annotations=[
            dict(text="Brand:", showarrow=False,
                                 x=0, y=1.08, yref="paper", align="left")
        ]
    )
    
    fig.write_html('test.html')
    
    fig.show()
    

    将两个系列一起绘制在同一个情节上会更复杂。我决定做单独的系列情节。您可以通过将df_temp = final_df2.query(f'brand== "{type}"')[y2] 行中的 y2 更改为 y1 来生成其他系列图。

    参考文献

    https://www.kaggle.com/jrmistry/plotly-how-to-change-plot-data-using-dropdowns

    https://plotly.com/python/custom-buttons/

    输出

    【讨论】:

    • 它不会将下拉列表写入 html。它只是写当前的数字
    • @MubashirRaza 如果您不介意,请分享您的代码和输出,我会看看我能提供什么帮助。你在使用 Jupyter Notebook 吗?
    • 刚刚添加。请检查
    • 真的需要保存这个,否则我将不得不付出很多努力才能将它完全改成情节
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2017-05-10
    • 2021-06-12
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    相关资源
    最近更新 更多