首页 > 解决方案 > Plotly:如何从 x 轴删除空日期?

问题描述

我有一个数据框

   Date        Category    Sum
0  2019-06-03    "25M"      34
1  2019-06-03    "25M"      60
2  2019-06-03    "50M"      23
3  2019-06-04    "25M"      67
4  2019-06-05    "50M"     -90
5  2019-06-05    "50M"     100
6  2019-06-06    "100M"     6
7  2019-06-07    "25M"     -100
8  2019-06-08    "100M"     67
9  2019-06-09    "25M"      450
10 2019-06-10    "50M"      600
11 2019-06-11    "25M"      -9
12 2019-07-12    "50M"      45
13 2019-07-13    "50M"      67
14 2019-07-14    "100M"    130
15 2019-07-14    "50M"      45
16 2019-07-15    "100M"    100
17 2019-07-16    "25M"     -90
18 2019-07-17    "25M"     700
19 2019-07-18    "25M"     -9

我想创建一个绘图图,显示在每个描述的日期上为不同的“类别”添加了“总和”,但如果日期没有任何数据,我想删除它们。

代码

df["Date"]=pd.to_datetime(df["Date"], format=("%Y%m%d"))
df=df.sort_values(["Date","Category","Sum"],ascending=False)
df=round(df.groupby(["Date","Category"]).agg({"Sum":"sum"}).reset_index(),1)


fig = px.bar(df, x=df["Date"] , y='Sum',barmode="group",color="Category") 
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
    buttons=list([
        dict(count=1, label="day", step="day", stepmode="todate"),
        dict(count=24, label="montly", step="month", stepmode="todate"),
        dict(count=1, label="year", step="year", stepmode="todate"),
        dict(step="all")
    ])
   ))


fig.show()

在此处输入图像描述

我得到这样的图表,但我想从绘图图中删除空日期

标签: pythonplotlyplotly-dashplotly-python

解决方案


我的图表也有同样的问题。只需将以下内容添加到布局代码中:

xaxis=dict(type = "category")

注意:我使用过import plotly.graph_objs as go不是 import plotly.express as px

这对我有用。希望对你也有帮助。


推荐阅读