【问题标题】:Plotly: How to plot time graph based on period?Plotly:如何根据周期绘制时间图?
【发布时间】:2020-02-05 06:22:25
【问题描述】:

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

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)

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

【问题讨论】:

标签: python pandas plotly


【解决方案1】:

如果通过YearMonthDay 列的 3 列 DataFrame 和 Series.dt.to_period 的月份周期,您可以创建由 to_datetime 填充的新列:

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      per
0  2017     1    dead             20 2017-01-01  2017-01
1  2018     1   alive             21 2018-01-01  2018-01
2  2018     2   alive             19 2018-02-01  2018-02
3  2019     3   empty             18 2019-03-01  2019-03

然后可以用句点或日期时间绘制:

dfy.plot(x='per', y='outcome_count')
dfy.plot(x='dates', y='outcome_count')

【讨论】:

  • 如何在同一张图上为每个结果绘制折线图,​​比如有死、活和空
  • @LivingstoneM - 你认为pivot 喜欢df = dfy.pivot('per','Outcome','outcome_count') 然后df.plot() 吗?
  • 或者类似df = dfy.pivot('per','Outcome','outcome_count').ffill() ?
【解决方案2】:

您的数据集非常有限。在 jezrael 的方法的基础上,我能够产生这个:

如果这确实是您要查找的内容,我可以解释详细信息。 如果没有,那么我相信我们会找到另一种方法。

这是目前为止的代码:

import pandas as pd 
import plotly.graph_objects as go
import 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 jezrael
dfy['dates'] = pd.to_datetime(dfy[['Year','Month']].assign(Day=1))
dfy['per'] = dfy['dates'].dt.to_period('m')

# periods as string
dfy['period']=[d.strftime('%Y-%m') for d in dfy['dates']]

# unique outcomes
outcomes = dfy['Outcome'].unique()

# plotly setup
fig = go.Figure()

# one trace per outcome
for 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()

【讨论】:

  • @LivingstoneM 我很高兴听到这个消息!由于 jezrael 理所当然地获得了接受标记,如果我的贡献对您有任何帮助,我可以直言不讳地指导您点击投票按钮吗?
  • 好,先生。一直很有用
  • @LivingstoneM 谢谢! 要求投票是一个完全的禁忌,但我认为这次是为了解决你的挑战是一个明确的团队努力。
  • @LivingstoneM 请原谅我的提问,但您介意我邀请您到chat 待一会儿吗?
猜你喜欢
  • 2023-01-18
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
  • 2019-07-25
  • 1970-01-01
  • 2019-12-11
相关资源
最近更新 更多