带有 editable 破折号 table 的条形图

Bar graph with editable dash table

我正在尝试使用 editable 破折号 table 制作条形图,但图表仅更改一次。在 table 中更改数据后,图表得到更新,但与我的预期不同。

下面是我的示例代码:

from dash_table import DataTable
from dash.dependencies import Input, Output
import dash
import dash_html_components as html
import dash_core_components as dcc
import pandas as pd
import plotly.graph_objs as go


raw_data = {'Type': ["Cash", "Credit Card"],
        'Rate': [50,50]}
test_df = pd.DataFrame(raw_data)
test_df['id'] = test_df['Type']
test_df.set_index('id', inplace=True, drop=False)

app = dash.Dash(__name__)
app.layout = html.Div(children=[
    dash_table.DataTable(
        id='table',
        data=test_df.to_dict('records'),editable=True,
        columns=[
            {"name": i, "id": i, "deletable": True, "selectable": True, "hideable": True}
            if i == "Type" or i == "Rate"
            else {"name": i, "id": i, "deletable": True, "selectable": True}
            for i in test_df.columns
        ],
        style_cell={
            'minWidth': '0px',
            'maxWidth': '180px',
            'whiteSpace': 'no-wrap',
            'overflow': 'hidden',
            'textOverflow': 'ellipsis'},
        style_table={'overflowX': 'scroll'},
        row_deletable=True
    ),
    dcc.Graph(
        id='plot',
        style={"max-width": "600px",
               "margin": "auto",
               "display": "inline-block"})
])


@app.callback(Output('plot', 'figure'),
              [Input('table', 'data'),
              Input('table', 'columns')])

def update_graph(data, cols):
    df = pd.DataFrame(data, columns=[c['name'] for c in cols])
    figure_2 = go.Figure(data=[
    go.Bar(x=df['Type'],
           y=df['Rate'],
           width=0.45,
           text = df['Rate'],
           textposition='inside',
           marker_color='indianred')])
    return figure_2

if __name__ == '__main__':
    app.run_server(port=1211, debug=False)

我第一次更改,图表如下所示:

但是从第二次开始,图表看起来像这样:

我应该怎么做才能解决这个问题。 实际上我阅读了 editable 文档,但我仍然不明白。 docs中的Graph是这样生成的:

def display_output(rows, columns):
    return {
        'data': [{
            'type': 'heatmap',
            'z': [[row.get(c['id'], None) for c in columns] for row in rows],
            'x': [c['name'] for c in columns]
        }]
    }

我不知道如何将它应用于条形图。

谢谢。

如果您在 data 的回调中放置打印语句,您将在初始加载时看到数据符合预期

[{'Type': 'Cash', 'Rate': 50, 'id': 'Cash'}, {'Type': 'Credit Card', 'Rate': 50, 'id': 'Credit Card'}]

Rate 保存一个数值。

但是当编辑数据中的值时table 值可以是任何东西,所以破折号 table 将您的输入视为字符串而不是数字。

因此,编辑 Rate 列中的值后,data 现在看起来像这样

[{'Type': 'Cash', 'Rate': 50, 'id': 'Cash'}, {'Type': 'Credit Card', 'Rate': '200', 'id': 'Credit Card'}]

我在200中填写的值现在是data中的一个字符串。

当两个 Rate 值都是字符串值时,plotly 似乎不知道应该如何绘制条形图了。

您可以将 dfRate 列转换为数字。

df['Rate'] = pd.to_numeric(df['Rate'])