我是破折号新手,正在努力创建多线图。我有一个数据并使用破折号绘制它并创建了一个多线图表。下面给出了可重现的代码-
import pandas as pd
import plotly.express as px
from dash import Dash, dcc, html, callback, Output, Input
df = pd.DataFrame({
'foo': ['ab','ab','ab','ab', 'es','es','es','es', 'la','la','la','la', 'kl','kl','kl','kl', 'ys','ys','ys','ys'],
'months': [1,3,6,12,1,3,6,12,1,3,6,12,1,3,6,12,1,3,6,12],
'metric': [60.25,70.96,104.72,194.33,60.27,72.52,117.66,234.53,61.17,72.30,118.84,239.15,60.76,72.53,118.39,239.00,59.00,65.41,78.04,123.49]
})
app = Dash()
app.layout = (html.Div([
html.H1(children='Metric assessment', style={'textAlign':'center'}),
html.Div(["Enter multiplier for metric ", dcc.Input(
id="some_number",
type="number",
placeholder=1, min = 1, max = 20, style={"margin-left": "15px"}
),
dcc.Graph(id='graph-content')
])
])
)
@callback(
Output('graph-content', 'figure'),
Input("some_number", "value")
)
def update_graph(some_number):
dff = df.copy(deep = True)
if not some_number:
some_number = 1
dff['Total metric'] = dff['metric']*some_number
dff['Total metric'] = dff['Total metric'].map('{:,.2f}'.format)
# dff = dff.sort_values(by = 'Total metric')
fig = px.line(dff, x='months', y='Total metric', color = 'foo', markers=True, title = 'Metric vs months')
return fig
if __name__ == '__main__':
app.run(debug=True)
即使在“总指标”列上对数据帧进行排序后,问题仍然存在。我该怎么做才能消除这个问题并获得正确的图表?
在回调中,“总指标”列被格式化(即作为字符串),因此 Plotly 将图中的相应数据处理为分类数据而不是数字数据。您可以使用
pandas.DataFrame.astype()
来解决这个问题:
dff['Total metric'] = dff['Total metric'].map('{:,.2f}'.format).astype(float)