python - 为什么 plotly express 会在时间线上抛出数据点?
问题描述
我有一个包含两列的简单数据框。示例如下所示,数据可在此处获得。
year-week users
0 2018-22 2
1 2018-23 3
2 2018-24 4
3 2018-25 3
4 2018-26 5
.. ... ...
69 2020-03 232
70 2020-04 226
71 2020-05 214
72 2020-06 203
73 2020-07 119
[74 rows x 2 columns]
当我尝试使用 Plotly Express 绘制这两列时,它会省略数据,直到2019-30
.
import pandas
import plotly.express as px
df = pd.read_csv("https://pastebin.com/raw/x164p1Zp")
fig = px.line(df, x="year-week", y="users")
fig.update_layout(xaxis=dict(tickformat="%Y-%W"))
fig.show()
如果我用 matplotlib 绘制相同的数据,则显示数据:
import pandas
import matplotlib
df = pd.read_csv("https://pastebin.com/raw/x164p1Zp")
df.plot.line(x="year-week", y="users");
我不明白为什么两个绘图库以截然不同的方式显示相同的数据。
如何在 Plotly Express 中绘制所有数据点以获得类似于 matplotlib 显示的图?
解决方案
Plotly 不会将您的 x 轴识别为日期。您需要将其显式转换为日期时间格式。
解决方案:
df = pd.read_csv("https://pastebin.com/raw/x164p1Zp")
# convert column to datetime, weekday needed for conversion to work
df["year-week"] = pd.to_datetime(df["year-week"] + '-0', format="%Y-%W-%w")
fig = px.line(df, x="year-week", y="users")
fig.update_layout(xaxis=dict(tickformat="%Y-%W"))
fig.show()
推荐阅读
- google-bigquery - 从 bigquery 脚本获取结果
- javascript - ReactJS Hook 错误处理不会捕获错误
- c - 字符串复制功能无法正确复制字符串。我的代码有什么问题?
- c# - Xamarin 表单 CollectionView 预选不工作
- python - 从matlab到python的随机三对角矩阵
- r - 当向量中存在不同类型的数据类型时,R编程语言在什么基础上执行强制转换
- opencart-3 - 类别页面上的 Opencart 产品类别 ID
- reactjs - 如何在 React Native 的选项卡中嵌套导航?
- python - 如何在 Python 中检查视频是否有声音?
- css - 如何在 Angular 组件中设置 ::before 伪元素的 CSS 属性?