Skip to main content
 首页 » 编程设计

python之如何根据日期列更改线图的颜色

2024年11月01日9zfyouxi

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

我试过代码:

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'), '', '', '', '', '') 

请您参考如下方法:

px.line 中的

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

剧情:

下面的代码片段生成了一堆随机日期,将月份数字提取为整数,将其添加到鸢尾花数据集,并让 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"。

请告诉我这对您来说效果如何。