python - I can't get the x-axis to work the way I want
问题描述
I'm using px.bar to plot profit and loss for each trading day. The problem is plotly is changing the order of the dates. Is there a way to force plotly to keep the order of the dataframe? I have tried to plot without the color assigned and then go back and update the color but I am not having any luck.
this is my line of code to plot the dataframe
fig1 = px.bar(dfff, x="DATE", y="Profit/Loss", color = "Marker", color_discrete_map = "identity").update_layout(showlegend=False, title_x=0.5)
Here is the dataframe.
DATE Profit/Loss Marker Cumulative_PnL Daily_Volume WinRate WinStreak CumulativeWinRate
08/16/21 -58.1995 red -58.1995 604.0000 80.0000 0 80.0000
08/17/21 -4.7700 red -62.9695 4.0000 50.0000 0 71.4286
08/18/21 31.4984 green -31.4711 1908.0000 100.0000 1 84.6154
08/20/21 49.6200 green 18.1489 1006.0000 50.0000 2 76.4706
08/23/21 -930.1800 red -912.0311 712.0000 50.0000 0 66.6667
08/24/21 99.1000 green -812.9311 306.0000 100.0000 1 70.9677
08/25/21 -0.6400 red -813.5711 332.0000 60.0000 0 67.3913
08/26/21 -50.0300 red -863.6011 2556.0000 66.6667 0 67.3077
08/27/21 -9.9100 red -873.5111 38.0000 81.8182 0 69.8413
08/30/21 7.8500 green -865.6611 424.0000 91.6667 1 73.3333
08/31/21 1.0000 green -864.6611 40.0000 100.0000 2 74.0260
解决方案
您的DATE
列是字符串类型。您需要将其转换为 datetime 类型才能plotly
正确识别:
df['DATE'] = pd.to_datetime(df.DATE, format='%m/%d/%y')
之后它应该正确绘制:
fig1 = px.bar(df, x="DATE", y="Profit/Loss", color = "Marker", color_discrete_map = "identity").update_layout(showlegend=False, title_x=0.5)
fig1.show()
另请参阅完整示例
推荐阅读
- google-chrome - A4 尺寸的 SVG 不能在打印中填满整个 A4 纸
- gatsby - 如何从 Gatsbyjs 中另一个节点上的 url 字段下载图像,以便我可以使用 gatsby-image?
- excel - Excel VBA:将动态变量分配给范围函数的问题
- php - PHP 邮件脚本运行多次(使用 Mailgun)
- javascript - 如何根据我的 Gridview Row 单击动态更改按钮的文本?
- lua - 是否有一个不会删除完整堆栈的 lua-c api 函数?
- anaconda - 自定义 conda 子频道
- android - 需要身份验证的Android Keystore,不是通过指纹解锁,而是仅通过密码解锁?
- laravel - 如何在 laravel eloquent 中检索具有多个条件的多个表数据?
- cmake - Cmake 可执行文件无法与依赖于另一个库的新接口库链接