【问题标题】:Plotly: how to stretch line over the graphics end?Plotly:如何在图形末端拉伸线?
【发布时间】:2020-10-17 08:15:36
【问题描述】:

我需要在图形区域的末尾延长线,这是由 2 个 DataFrame 点和 DatetimeIndex 组成的,如下面的屏幕所示:

如何做到这一点?用数学我会计算出直线与 x 轴的准确位置,买它是不可能的,因为你无法测量 1 月 4 日和 1 月 5 日之间的距离,因为它是 1 天。

import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({
    'score':[30, 60, 38, 10, 50, 70, 40],
    'date':['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07'],
})
df['date'] = pd.to_datetime(df['date'])

fig = go.Figure()
fig.add_shape(
    dict(
        type="line",
        x0=df.iloc[1]['date'],
        y0=df.iloc[1]['score'],
        x1=df.iloc[2]['date'],
        y1=df.iloc[2]['score'],
        line=dict(
        color="RoyalBlue",
        width=3
    )
))

fig.add_trace(
    go.Scatter(
        mode='markers',
        x=df['date'],
        y=df['score'],
        marker=dict(
            color='LightSkyBlue',
            size=12,
            line=dict(
                color='MediumPurple',
                width=4
            )
        ),
    )
)

fig.update_xaxes(tickmode='auto',)
fig.show()

【问题讨论】:

  • 你想要蓝色还是红色圆点?

标签: python pandas matplotlib plotly


【解决方案1】:

只要您以分钟为单位转换天数,这应该没什么大不了的。这里我已经为你计算好了日期


import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({
    'score':[30, 60, 38, 10, 50, 70, 40],
    'date':['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07'],
})
df['date'] = pd.to_datetime(df['date'])

fig = go.Figure()
fig.add_shape(
    dict(
        type="line",
        x0=df.iloc[1]['date'],
        y0=df.iloc[1]['score'],
        x1=df.iloc[2]['date'],
        y1=df.iloc[2]['score'],
        line=dict(
        color="RoyalBlue",
        width=3
    )
))
fig.add_shape(
    dict(
        type="line",
        x0=df.iloc[2]['date'],
        y0=df.iloc[2]['score'],
        x1=pd.Timestamp(2000,1,4,17,16),
        y1=0,
        line=dict(
        color="red",
        dash="dot",
        width=3
    )
))


fig.add_trace(
    go.Scatter(
        mode='markers',
        x=df['date'],
        y=df['score'],
        marker=dict(
            color='LightSkyBlue',
            size=12,
            line=dict(
                color='MediumPurple',
                width=4
            )
        ),
    )
)

fig.update_xaxes(tickmode='auto',)
fig.show()

【讨论】:

  • 兄弟,谢谢你的回复,但是翻译成分钟非常不方便。我的问题不仅仅是用红点制作图形,我有复杂的机器学习算法+绘图图形,这是不现实的,每一步都转换每个时间单位
  • @sirjay 我不明白反对意见。在您的问题中,您只要求一行,您说不可能这样做。
猜你喜欢
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多