首页 > 解决方案 > 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

标签: pythonplotlybar-chart

解决方案


您的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()

在此处输入图像描述

另请参阅完整示例


推荐阅读