用短划线图显示本月尚未发生的日子

问题描述 投票:0回答:1

大家早上好

我的代码遇到了一个小问题。下面列出了:

else:
            dff = df.query(f"year == {year_value}" and f"month == {month_value}" and f"desk == '{desk_value}'")
            day_totals = dff['day'].value_counts(sort=False)
            unique_days = dff['day'].unique()
            fig = px.bar(dff, x = unique_days, y = list(day_totals), text_auto=True)
            fig.update_layout(
                xaxis = dict(
                    tickmode = 'array',
                    tickvals = unique_days,
                    ticktext = unique_days,
                    title= "Day"
                ),
                yaxis = dict(
                    tickmode = 'array',
                    tickvals = list(day_totals),
                    ticktext = list(day_totals),
                    title= "patrons Helped"
                )
            )
            fig.update_traces(
                marker_color = '#376062'
            )
            return fig  

F 字符串是从下拉菜单中收集的值,只有在我尝试按桌面过滤的情况下才会发生这种情况。本质上,即使今天是 20 号,它也会显示 21 号、22 号、23 号等的数据。我只想要与所选要显示的月份相关的值。

我最近才注意到这一点,并没有尝试太多。我不想完全打破它,但我有一种不好的预感。我只是在寻找从哪里开始修复此问题的方向,以便它显示准确的数据。

python pandas dataframe plotly-dash dashboard
1个回答
0
投票

解决此问题的一种方法是生成该月的所有日期并使用这些值创建图表。您可以通过提供年份和月份并进行一些计算来获取该月的最后一天来创建日期范围索引。通过在当月开始时添加 31 天,您可以找到下个月的数字。

- timedelta(days=1)
从下个月的第一天移动到当月的最后一天。

all_days = pandas.date_range(
    start=date(year_value, month_value, 1),
    end=date(year_value, (date(year_value, month_value, 1) + timedelta(days=31)).month, 1
    ) - timedelta(days=1),
).day

一旦您拥有当月的所有天数,您就可以重新索引并填补数据中的空白,如下所示:

day_totals = dff["day"].value_counts().reindex(all_days, fill_value=0)
unique_days = all_days.values

我遇到了 df.query 无法正确过滤月份值的另一个问题,因此我将语法更改为一个大的 f 字符串,并在字符串中包含

and
关键字。

这是输出:

screenshot of the bar chart

这是完整的示例:

import random
from datetime import date, timedelta
import pandas
import plotly.express as px


def get_df():
    # Create some fake data for an example
    date_cursor = date(2024, 1, 1)
    desks = ["0001", "0002", "0003"]
    records = []
    while date_cursor <= date(2024, 6, 25):
        for desk in desks:
            for _ in range(random.randint(0, 5)):
                records.append(
                    [date_cursor.year, date_cursor.month, date_cursor.day, desk]
                )
        date_cursor += timedelta(days=1)
    return pandas.DataFrame(records, columns=["year", "month", "day", "desk"])


df = get_df()


year_value = 2024
month_value = 6
desk_value = "0001"


dff = df.query(
    f"year == {year_value} and month == {month_value} and desk == '{desk_value}'"
)

all_days = pandas.date_range(
    start=date(year_value, month_value, 1),
    end=date(
        year_value, (date(year_value, month_value, 1) + timedelta(days=31)).month, 1
    )
    - timedelta(days=1),
).day

day_totals = dff["day"].value_counts().reindex(all_days, fill_value=0)
unique_days = all_days.values
fig = px.bar(dff, x=unique_days, y=list(day_totals), text_auto=True)
fig.update_layout(
    xaxis=dict(
        tickmode="array", tickvals=unique_days, ticktext=unique_days, title="Day"
    ),
    yaxis=dict(
        tickmode="array",
        tickvals=list(day_totals),
        ticktext=list(day_totals),
        title="patrons Helped",
    ),
)
fig.update_traces(marker_color="#376062")
fig.show()
© www.soinside.com 2019 - 2024. All rights reserved.