matplotlib 折线图上的曲线

fsi0uk1n  于 2022-11-15  发布在  其他
关注(0)|答案(2)|浏览(185)

我有一个 Dataframe ,其中包含一个周列和每周捕获的数据。

  1. # Import pandas library
  2. import pandas as pd
  3. # initialize list of lists
  4. data = [['20', 10],
  5. ['21', 15],
  6. ['23', 14],
  7. ['40', 50],
  8. ['41', 56]]
  9. # Create the pandas DataFrame
  10. df = pd.DataFrame(data, columns=['weeks', 'counts'])
  11. # print dataframe.
  12. df

现在,我将使用此数据绘制折线图。请注意,从第23周至第40周,我们没有数据。因此,我打算在绘图中跳过这几周,只绘制具有可用数据的这些周的折线图。
Plotly命令一切自动,它包括失踪的几周,这可能会导致问题时,它被解释。
看看plotly怎么做

  1. import plotly.express as px
  2. #df = px.data.gapminder().query("country=='Canada'")
  3. fig = px.line(df, x="weeks", y="counts", title='Recruitment per Week')
  4. #fig.write_image("images/Recruit.jpeg")
  5. fig.show()

我怎么能在图表上有一个从第23周至第40周的休息。就像折线图一样,我们在这些特定的周没有数据。

lnlaulya

lnlaulya1#

您 是否 需要 经常 重复 此 操作 ? 您 是否 需要 灵活 的 解决 方案 或 仅 适用 于 此 情况 的 解决 方案 ? 您 可以 首先 检查 数据 帧 中 的 连续 值 , 然后 在 同一 图形 中 为 每个 连接 的 时段 创建 新 的 轨迹 。 您 还 可以 为 它们 指定 相同 的 颜色 , 以 使 其 更 易于 阅读 。 您 可以 手动 为 每个 连接 的 时段 创建 单独 的 数据 帧 , 然后 为 每个 数据 帧 创建 轨迹 。

ktca8awb

ktca8awb2#

首先,我会重新索引数据,以便将没有数据的周数计入。

  1. df['weeks'] = df['weeks'].astype(int)
  2. df = df.set_index('weeks').reindex(np.arange(df['weeks'].min(),df['weeks'].max()+1)).reset_index()
  3. >>> df
  4. weeks counts
  5. 0 20 10.0
  6. 1 21 15.0
  7. 2 22 NaN
  8. 3 23 14.0
  9. 4 24 NaN
  10. 5 25 NaN
  11. 6 26 NaN
  12. 7 27 NaN
  13. 8 28 NaN
  14. 9 29 NaN
  15. 10 30 NaN
  16. 11 31 NaN
  17. 12 32 NaN
  18. 13 33 NaN
  19. 14 34 NaN
  20. 15 35 NaN
  21. 16 36 NaN
  22. 17 37 NaN
  23. 18 38 NaN
  24. 19 39 NaN
  25. 20 40 50.0
  26. 21 41 56.0
  27. fig = px.line(df,
  28. x='weeks',
  29. y='counts',
  30. title='Recruitment per Week',
  31. markers=True)
  32. fig.show()

展开查看全部

相关问题