【问题标题】:Why doesn't Plotly (in Python3) make different lines in a linechart?为什么 Plotly(在 Python3 中)不在折线图中制作不同的线?
【发布时间】:2022-01-14 20:50:18
【问题描述】:

我正在尝试使用 Plotly for Python3 构建折线图。我的图表显示了随着时间的推移在 5 个州的 UFO 目击次数。但是,对于 5 个状态中的每一个,所有点都用一条线连接,而不是一条线。我怎样才能有意识地认识到数据具有不同的状态?我觉得我是用“文本”参数来做这件事的,但这没有用。

数据

    year    state   sightings
7   1930    NY         2    
10  1931    NY         1    
13  1933    NY         1    
16  1935    CA         2    
20  1937    CA         1

代码

import plotly.express as px # plotly library

fig = px.line(state_UFO_sightings, 
              x="year", 
              y="total", 
              text="sightings",
              title = "Top 5 states with most UFO sightings")
fig.show()

当前折线图

【问题讨论】:

  • 尝试关键字参数color 而不是text

标签: python plotly


【解决方案1】:

用途:

color="state"

在你的绘图函数中。

【讨论】:

    【解决方案2】:
    • 数据集在 kaggle 上。用过这个。
    • 三个参数的简单案例px.line()
    • key 为color 参数。您的图表可以解释为您在单个跟踪中混合状态
    import plotly.express as px
    import pandas as pd
    import kaggle.cli
    import sys, requests
    from pathlib import Path
    from zipfile import ZipFile
    import urllib
    
    # download some images to demonstrate
    url = "https://www.kaggle.com/NUFORC/ufo-sightings"
    sys.argv = [sys.argv[0]] + f"datasets download {urllib.parse.urlparse(url).path[1:]}".split(" ")
    kaggle.cli.main()
    
    zfile = ZipFile(f'{urllib.parse.urlparse(url).path.split("/")[-1]}.zip')
    dfs = {f.filename: pd.read_csv(zfile.open(f), on_bad_lines="skip", low_memory=False)for f in zfile.infolist()}
    
    df = dfs["complete.csv"]
    df["datetime"] = pd.to_datetime(df["datetime"], errors="coerce")
    
    # calculate sightings
    df = (
        df.loc[df["country"].eq("us")]
        .groupby([df["datetime"].dt.year, "state"], as_index=False)
        .size()
        .rename(columns={"datetime": "year", "size": "sightings"})
    )
    
    # top 5 states over all time
    df = df.loc[
        df["state"].isin(
            df.groupby("state")
            .agg({"sightings": "sum"})
            .sort_values("sightings", ascending=0)
            .head(5)
            .index
        )
    ]
    
    px.line(df, x="year", y="sightings", color="state")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-02
      • 2020-04-24
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2021-07-29
      相关资源
      最近更新 更多