【问题标题】:How to change color of line plot based on date column?如何根据日期列更改线图的颜色?
【发布时间】:2020-02-07 16:09:17
【问题描述】:

我正在尝试根据“日期列”更改折线图的颜色。但我收到一个错误

我已经尝试过代码:

fig = px.line(df_1, x='Time_ist', y='AccelerationG', color = 'Date')
# # fig.update_layout(title_text='Acceleration on ' + str(i))
fig.show()

The error i am getting is:

KeyError: (Timestamp('2019-09-26 00:00:00'), '', '', '', '', '')

【问题讨论】:

    标签: python pandas plotly


    【解决方案1】:

    px.line 中的color 不采用Timestamp 作为参数。如果它以某种方式发生了,我不确定结果会是什么。也许是一种表明时间流逝的颜色?我不确定,真的。但我猜你在这里寻找的是按一年中的月份或日期识别数据点,并将其作为一个因素或类别进行说明。我将使用来自plotly 的示例和来自SO 帖子Generating random dates within a given range in pandas 的建议来展示如何执行后者。

    剧情:

    下面的 sn-p 生成一堆随机日期,将月份数字提取为整数,将其添加到 iris 数据集,并让px.Scatter() 将其用作着色的输入。

    代码:

    # Load example from https://plot.ly/python/creating-and-updating-figures/
    import plotly.express as px
    import pandas as pd
    import numpy as np
    
    iris = px.data.iris()
    
    # Add random dates using a suggestion from https://stackoverflow.com/questions/50559078/generating-random-dates-within-a-given-range-in-pandas
    def random_dates(start, end, n, seed=1, replace=True):
        dates = pd.date_range(start, end).to_series()
        return dates.sample(n, replace=replace, random_state=seed)
    
    dates=random_dates("20190101","20191212", len(iris), seed=1)
    months=[m.month for m in dates]
    iris['month']=months
    
    fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="month")
    fig.show()
    

    如果您想使用月份,只需将months=[m.month for m in dates] 更改为days=[m.day for d in dates],并将px.Scatter 中的引用从color="month" 调整为color="days"

    请告诉我这对你有什么影响。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 2020-03-09
      • 2012-03-14
      相关资源
      最近更新 更多