Dash Plotly 如何修复 "All arguments should have the same length. x and y"

Dash Plotly how to fix "All arguments should have the same length. x and y"

我正在使用 Dash Plotly 制作图表。 当x和y长度相等时,Dash会显示图表,但当x和y长度不相等时,会报错。

这里是错误:

ValueError: All arguments should have the same length. The length of argument `y` is 3, whereas the length of  previously-processed arguments ['x'] is 368

x 值:

DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04',
           '2017-01-05', '2017-01-06', '2017-01-07', '2017-01-08',
           '2017-01-09', '2017-01-10',
           ...
           '2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28',
           '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01',
           '2018-01-02', '2018-01-03'],
          dtype='datetime64[ns]', length=368, freq='D')

Y值:

0                                     Violent protests
1    Confrontational protests (illegal and non viol...
7        Demonstrative protests (legal and nonviolent)

和图表:

graph = px.line(df, x=Date, y=Categories,  color=Categories, markers=True,)

我要制作这张图表:

如何解决问题并制作此图表?

更新 1

整体数据:

图表的生成逻辑:

这张图片显示了上面的图表是如何使用 excel 生成的。

我想使用 Dash Plotly 生成相同的图表。

更新 2

CSV 文件中的所有数据:

id  date_x  Agency  Relevance_x Human_Validation    Event   Categories of event start date  end date    Duration    Issue   Local-National  Location_Category   Location_Province   Oganizer_type   CivilSocietySector  MainPoliticalSector CS_Location_Category    CS_Location_Province    size_of_participants    Arena_type  Arena_Province
45803   1/1/2018 7:19   ILNA    Yes 1   Protest Violent protests    12/29/2017  12/29/2017  1   Economic    National    Town    Khuzestan   Unknown None    Neutral National    NONE    unknown Streets Khuzestan
45817   1/1/2018 7:46   ILNA    Yes 1   Protest Confrontational protests (illegal and non violent)          1   Labour  Local   City    Azerbaijan, East    Workers Labour  Neutral Province Center Azerbaijan, East    medium group <50    Working places  Azerbaijan, East
45531   1/1/2018 18:17  ILNA    Yes 1   Protest Violent protests            1   Economic    National    City    Isfahan Unknown None    Neutral National    NONE    unknown Streets Isfahan
45529   1/1/2018 18:23  ILNA    Yes 1   Protest Violent protests            1   Economic    National    Province Center Markazi Unknown None    Neutral National    NONE    unknown Streets Markazi
45448   1/2/2018 6:36   ILNA    Yes 1   Protest Violent protests            1   Economic    National    Province Center Kurdistan   Unknown None    Neutral National    NONE    unknown Streets Kurdistan
45299   1/2/2018 10:05  ILNA    Yes 1   Protest Confrontational protests (illegal and non violent)          1   Economic    National    Capital Tehran  Unknown Student Movement    Neutral Capital Tehran  unknown University campuses Tehran
45029   1/3/2018 6:43   ILNA    Yes 1   Protest Violent protests            1   Economic    National    Town    Kermanshah  Unknown None    Neutral National    NONE    unknown Streets Kermanshah
44950   1/3/2018 8:49   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    Province Center Bushehr GONGO   Progovernment   Conservative    National    Bushehr unknown Streets Bushehr
44935   1/3/2018 9:22   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    Province Center Khuzestan   GONGO   Progovernment   Conservative    National    Khuzestan   unknown Streets Khuzestan
44935   1/3/2018 9:22   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    City    Khuzestan   GONGO   Progovernment   Conservative    National    Khuzestan   unknown Streets Khuzestan
44935   1/5/2018 9:22   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    City    Khuzestan   GONGO   Progovernment   Conservative    National    Khuzestan   unknown Streets Khuzestan
  • 始终以文本而非图像形式提供示例数据
  • 这很容易绘制,基于结构化数据。将 date 保留在索引中,每一列都是一行,它简化为 px.line(dfp, markers=True)
  • 您问题的核心是您传递的数组不一致。使用结构化数据框
import pandas as pd
import numpy as np
import plotly.express as px

# fmt: off
L=24*5
events=["Protest"]
cat = ["Violent protests","Confrontational protests (illegal and non violent)","Demonstrative protests (legal and nonviolent"]
iss = ["Economic","Political","Labour"]
ln = ["Local","National"]

# generate some sample data...
df = pd.DataFrame({"date_x":pd.date_range("1-jan-2018", freq="1H", periods=L), "Event":np.random.choice(events,L),
             "Categories of event":np.random.choice(cat, L), "Issue":np.random.choice(iss,L), "Local-National":np.random.choice(ln, L)})
# fmt: on
df = df.sample(50)  # take random subset of data so total events varies by day
# sumarise data frame for plotting.  NB dates are in the index
dfp = (
    df.groupby([df["date_x"].dt.date, "Categories of event"])
    .size()
    .unstack("Categories of event")
    .assign(Events=lambda d: d.sum(axis=1))
).fillna(0)
# now it's very simple to plot...
px.line(dfp, markers=True).update_layout(
    xaxis={"dtick":"D"},
    legend=dict(
        yanchor="bottom", y=-1, xanchor="center", title_text="", x=.5
    ),
)

已更新 - 使用提供的样本数据

  • 确保 date_x 是正确的数据类型
  • 驱动总数的列是 事件
import io
import pandas as pd
import plotly.express as px

# fmt: off
df = pd.read_csv(io.StringIO("""id  date_x  Agency  Relevance_x Human_Validation    Event   Categories of event start date  end date    Duration    Issue   Local-National  Location_Category   Location_Province   Oganizer_type   CivilSocietySector  MainPoliticalSector CS_Location_Category    CS_Location_Province    size_of_participants    Arena_type  Arena_Province
45803   1/1/2018 7:19   ILNA    Yes 1   Protest Violent protests    12/29/2017  12/29/2017  1   Economic    National    Town    Khuzestan   Unknown None    Neutral National    NONE    unknown Streets Khuzestan
45817   1/1/2018 7:46   ILNA    Yes 1   Protest Confrontational protests (illegal and non violent)          1   Labour  Local   City    Azerbaijan, East    Workers Labour  Neutral Province Center Azerbaijan, East    medium group <50    Working places  Azerbaijan, East
45531   1/1/2018 18:17  ILNA    Yes 1   Protest Violent protests            1   Economic    National    City    Isfahan Unknown None    Neutral National    NONE    unknown Streets Isfahan
45529   1/1/2018 18:23  ILNA    Yes 1   Protest Violent protests            1   Economic    National    Province Center Markazi Unknown None    Neutral National    NONE    unknown Streets Markazi
45448   1/2/2018 6:36   ILNA    Yes 1   Protest Violent protests            1   Economic    National    Province Center Kurdistan   Unknown None    Neutral National    NONE    unknown Streets Kurdistan
45299   1/2/2018 10:05  ILNA    Yes 1   Protest Confrontational protests (illegal and non violent)          1   Economic    National    Capital Tehran  Unknown Student Movement    Neutral Capital Tehran  unknown University campuses Tehran
45029   1/3/2018 6:43   ILNA    Yes 1   Protest Violent protests            1   Economic    National    Town    Kermanshah  Unknown None    Neutral National    NONE    unknown Streets Kermanshah
44950   1/3/2018 8:49   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    Province Center Bushehr GONGO   Progovernment   Conservative    National    Bushehr unknown Streets Bushehr
44935   1/3/2018 9:22   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    Province Center Khuzestan   GONGO   Progovernment   Conservative    National    Khuzestan   unknown Streets Khuzestan
44935   1/3/2018 9:22   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    City    Khuzestan   GONGO   Progovernment   Conservative    National    Khuzestan   unknown Streets Khuzestan
44935   1/5/2018 9:22   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    City    Khuzestan   GONGO   Progovernment   Conservative    National    Khuzestan   unknown Streets Khuzestan"""), 
                 sep="\s\s+", engine="python")
# fmt: on

df["date_x"] = pd.to_datetime(df["date_x"])
dfp = (
    df.groupby([df["date_x"].dt.date, "Event"])
    .size()
    .unstack("Event")
    .assign(Events=lambda d: d.sum(axis=1))
).fillna(0)

# now it's very simple to plot...
px.line(dfp, markers=True).update_layout(
    xaxis={"dtick":"D"},
    legend=dict(
        yanchor="bottom", y=-1, xanchor="center", title_text="", x=.5
    ),
)