【问题标题】:Why I am getting an error with plotly line chart为什么我在绘制折线图时出现错误
【发布时间】:2021-09-03 05:28:26
【问题描述】:

我是 Plotly 的新手,正在尝试使用 Plotly 折线图绘制下面的数据透视表。我的代码如下。错误也附在这里。

请问我哪里出错了

  # create traces
    trace0 = go.Scatter(
        x = df_50_08_16_PVT['Device_ID'],
        y = df_50_08_16_PVT['NoiseLevel[dB]'],
        mode = 'lines+markers',
        name = 'Noise Level'
    )
    trace1 = go.Scatter(
        x = df_50_08_16_PVT['Device_ID'],
        y = df_50_08_16_PVT['SPEC_MAX'],
        mode = 'lines+markers',
        name = 'SPEC_MAX'
    )
    data = [trace0, trace1]  # assign traces to data
    layout = go.Layout(
        title = 'Line chart showing three different modes'
    )
    fig = go.Figure(data=data,layout=layout)
    pyo.plot(fig, filename='line1.html')

正如 Rob 提到的,我使用了 Index.get_level_values(level) 并且图形即将到来,但不是以预期的方式。请在下面查看我获得的和预期的图表

预期

【问题讨论】:

  • 看起来 Device_ID 是多索引的一部分。这行代码将独立失败df_50_08_16_PVT['Device_ID']。考虑使用pandas.pydata.org/pandas-docs/stable/reference/api/…
  • 这是一个多索引数据透视表。
  • 是的 - 我的观点。所以你不能像一列一样引用索引的一部分
  • 像这样改变 X 轴 'x = df_50_08_16_PVT.index.get_level_values('Device_ID')' 可以吗

标签: python pandas plot plotly plotly-dash


【解决方案1】:
  • 你没有提供样本数据,所以我模拟了
  • 您的初始错误是直接的pandas 编码错误。您需要使用get_level_values 引用索引中的值
  • 您的图表在直接切换后是spikey,因为多个 y 值共享相同的 x 轴值
  • 仅使用索引位置 (reset_index().index) 即可解决此问题
  • 现在需要构建 x 轴以包含 Device_ID
  • 终于修复了hovertemplate
import random
import numpy as np
import pandas as pd
import plotly.graph_objects as go

# question has no data, generate some...
df_50_08_16_PVT = pd.concat(
    [
        pd.DataFrame(
            index=pd.MultiIndex.from_product(
                [
                    [f"{h}_{n}" for n in np.random.randint(1000, 2000, 4)],
                    list("abcdefghijklmnop")[0 : random.randint(4, 15)],
                ],
                names=["Device_ID", "filler"],
            )
        )
        for h in ["SF", "TT"]
    ]
).pipe(
    lambda d: d.sort_index().assign(
        **{
            "NoiseLevel[dB]": np.random.uniform(-97, -102, len(d)),
            "SPEC_MAX": np.random.uniform(-96.5, -97, len(d)),
        }
    )
)


# build array has first instance of Device_ID and every other value empty string
s = (
    df_50_08_16_PVT.index.get_level_values("Device_ID")
    .to_series()
    .groupby("Device_ID")
    .cumcount()
)
ticks = np.where(s == 0, s.index, "")

fig = go.Figure(
    data=[
        go.Scatter(
            x=df_50_08_16_PVT.reset_index().index,
            y=df_50_08_16_PVT[c],
            mode="lines+markers",
            meta=df_50_08_16_PVT.index.get_level_values("Device_ID"),
            name=c,
            hovertemplate="(%{meta},%{y})",
        )
        for c in df_50_08_16_PVT.columns
    ],
    layout={
        "title": "Line chart showing three different modes",
        "xaxis": {
            "ticktext": ticks,
            "tickmode": "array",
            "tickvals": df_50_08_16_PVT.reset_index().index,
        },
    },
)
fig

【讨论】:

  • 对于像我这样的人来说,这段代码需要学习很多东西。我可以知道数组 'S' 和 'ticks' 在这里做什么
  • plotly.com/python/tick-formatting/#tickmode--array 定义了如何构建数组以在 x 轴上实现我们想要的标签。 ticksticktext s 是我用来构建这个数组的系列
  • 我可以知道这里发生了什么吗? ticks = np.where(s == 0, s.index, "") "
  • “meta=df_50_08_16_PVT.index.get_level_values("Device_ID")”如何映射到X轴
  • 这是“最终修复悬停模板”的注释。需要在 hovertemplate 中使用的值
猜你喜欢
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 2013-12-07
  • 2022-01-03
  • 2021-10-07
  • 1970-01-01
  • 2018-09-02
  • 2020-10-03
相关资源
最近更新 更多