Plotly.express、熊猫和 NaN
Posted
技术标签:
【中文标题】Plotly.express、熊猫和 NaN【英文标题】:Plotly.express, pandas and NaNs 【发布时间】:2021-12-15 19:26:21 【问题描述】:根据下面的代码,我想以绘图方式可视化我的数据。但是,我创建的饼图也显示了 Null,我想省略它。
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
df = pd.DataFrame([
['January', 'Violin'],
['February', 'Piano'],
['March', 'Violin'],
['February', 'Violin'],
['January', 'Piano'],
['January', 'Violin']],
columns=['Month', 'Instrument']
)
df = df.pivot(columns='Month', values='Instrument')
app = dash.Dash(__name__)
app.layout = html.Div([
html.P("Select a month:"),
dcc.Dropdown(
id='my_dropdown',
value = 'January',
options=[
'label': 'January', 'value': 'January',
'label': 'February', 'value': 'February',
'label': 'March', 'value': 'March'
],
clearable=False,
style="width": "50%"
),
dcc.Graph(id="pie-chart"),
])
@app.callback(
Output("pie-chart", "figure"),
[Input("my_dropdown", "value")])
def generate_chart(my_dropdown):
fig = px.pie(df, names=my_dropdown)
return fig
app.run_server(debug=True)
在这种情况下,我应该将某些内容更改为代码的情节部分,还是应该以不同的方式转换我的初始 DataFrame(而不是使用 df.pivot() 选项)?
【问题讨论】:
【参考方案1】:看起来你想要的是每个仪器实例数的计数,所以我认为你不需要旋转你的 DataFrame。你可以保持原样:
df
Month Instrument
0 January Violin
1 February Piano
2 March Violin
3 February Violin
4 January Piano
5 January Violin
如果您将参数names='Instrument'
传递给px.pie
,它将通过计算Instrument
列中唯一值的出现次数来创建饼图,您不必担心出现空值。然后,您可以按用户在 generate_chart
函数中以破折号选择的月份对 DataFrame 进行子集化。
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
df = pd.DataFrame([
['January', 'Violin'],
['February', 'Piano'],
['March', 'Violin'],
['February', 'Violin'],
['January', 'Piano'],
['January', 'Violin']],
columns=['Month', 'Instrument']
)
# df = df.pivot(columns='Month', values='Instrument')
app = dash.Dash(__name__)
app.layout = html.Div([
html.P("Select a month:"),
dcc.Dropdown(
id='my_dropdown',
value = 'January',
options=[
'label': 'January', 'value': 'January',
'label': 'February', 'value': 'February',
'label': 'March', 'value': 'March'
],
clearable=False,
style="width": "50%"
),
dcc.Graph(id="pie-chart"),
])
@app.callback(
Output("pie-chart", "figure"),
[Input("my_dropdown", "value")])
def generate_chart(my_dropdown):
fig = px.pie(
df[df['Month'] == my_dropdown],
names='Instrument'
)
# fig = px.pie(df, names=my_dropdown)
return fig
app.run_server(debug=True)
【讨论】:
以上是关于Plotly.express、熊猫和 NaN的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Python 中更改 plotly.express 的颜色和大小?
Plotly:如何在 Plotly Express 中注释多行?
如何在 Python 中使用 Plotly Express 仅显示图例的子集(plotly.express,px)?