猿问

Plotly:如何根据周期绘制时间图?

大家好,我有这个数据集:


import pandas as pd 


# intialise data of lists. 

data = {'Year':['2017', '2018', '2018', '2019'],'Month':['1', '1', '2', '3'],'Outcome':['dead', 'alive', 'alive', 'empty'], 'outcome_count':[20, 21, 19, 18]} 


# Create DataFrame 

dfy = pd.DataFrame(data) 


# Print the output. 

print(dfy)

我确实想根据应该是月份和年份的时期来绘制结果。现在,月份和年份在不同的列上,我如何将它们组合起来,以便我有一个相对于月份和年份的结果图表。传说应该有结果名?


手掌心
浏览 105回答 2
2回答

三国纷争

您可以创建由日期时间填充的新列,to_datetime如果通过 3 列 DataFrame 与Year, Month,Day列然后是月份周期Series.dt.to_period:dfy['dates'] = pd.to_datetime(dfy[['Year','Month']].assign(Day=1))dfy['per'] = dfy['dates'].dt.to_period('m')print(dfy)   Year Month Outcome  outcome_count      dates      per0  2017     1    dead             20 2017-01-01  2017-011  2018     1   alive             21 2018-01-01  2018-012  2018     2   alive             19 2018-02-01  2018-023  2019     3   empty             18 2019-03-01  2019-03然后可以用句点或日期时间绘制:dfy.plot(x='per', y='outcome_count')dfy.plot(x='dates', y='outcome_count')

慕沐林林

您的数据集非常有限。在 jezrael 的方法的基础上,我能够产生这个:https://i.stack.imgur.com/HZ0eR.png如果这实际上是您正在寻找的东西,我可以解释详细信息。如果没有,那么我相信我们会找到另一种方法。这是到目前为止的代码:import pandas as pd import plotly.graph_objects as goimport plotly.express as px# intialise data of lists. data = {'Year':['2017', '2018', '2018', '2019'],'Month':['1', '1', '2', '3'],'Outcome':['dead', 'alive', 'alive', 'empty'], 'outcome_count':[20, 21, 19, 18]} # Create DataFrame dfy = pd.DataFrame(data) # approach from jezraeldfy['dates'] = pd.to_datetime(dfy[['Year','Month']].assign(Day=1))dfy['per'] = dfy['dates'].dt.to_period('m')# periods as stringdfy['period']=[d.strftime('%Y-%m') for d in dfy['dates']]# unique outcomesoutcomes = dfy['Outcome'].unique()# plotly setupfig = go.Figure()# one trace per outcomefor outcome in outcomes:    df_plot = dfy[dfy['Outcome']==outcome]    fig.add_trace(go.Scatter(x=df_plot['period'], y=df_plot['outcome_count'],                             name=outcome                          ))fig.show()
随时随地看视频慕课网APP

相关分类

Python
我要回答