python-plotly 相对于语言环境的日期格式

问题描述 投票:0回答:2

我正在使用 python

plotly
库来绘制一些时间序列。我遇到的问题是,不知何故,情节不尊重我的区域设置。 请参阅以下代码:

import pandas as pd
import numpy as np
import plotly.express as px
from datetime import datetime
import locale


#Get information on the actual locale setting:
print(locale.getlocale())


#Set locale for another country:
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8') # this sets the date time formats to Germany; there are many other options for currency, numbers etc. 
#for any other locale settings see: https://docs.python.org/3/library/locale.html

d = {'Time': [datetime(2020, k, 15) for k in range(2,7)],
      'value': np.random.rand(5)}
df=pd.DataFrame(d)
print(df)
print(df.info())
print(df["Time"].dt.strftime("%a %H:%M"))

fig = px.line(df, y="value", x="Time")
fig.update_xaxes(
    tickformat="%a\n%H:%M",
)
fig.show()

在控制台上给出以下输出:

('de_DE', 'UTF-8')
        Time     value
0 2020-02-15  0.541681
1 2020-03-15  0.639813
2 2020-04-15  0.127375
3 2020-05-15  0.019197
4 2020-06-15  0.617402
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   Time    5 non-null      datetime64[ns]
 1   value   5 non-null      float64       
dtypes: datetime64[ns](1), float64(1)
memory usage: 208.0 bytes
None
0    Sa 00:00
1    So 00:00
2    Mi 00:00
3    Fr 00:00
4    Mo 00:00
Name: Time, dtype: object

以及下图:

我已经搜索了很多,但没有任何效果(我知道我可以在将时间戳传递给绘图之前将它们转换为字符串,但这不是一个好的风格),所以有人建议出了什么问题以及如何修复它?

python localization plotly plotly-python
2个回答
3
投票

从我目前可以发现的情况来看,Plotly 在更改语言环境时似乎没有更改日期格式等。处理这个问题的唯一方法似乎是转换字符串。这个答案的基础来自社区。开发者的评论截至 2021 年 7 月,因此未来可能会对此进行改进。另外,我的回答可能会帮助其他受访者找到解决此问题的方法。

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime
import locale

#Get information on the actual locale setting:
print(locale.getlocale())

#Set locale for another country:
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8') 
# this sets the date time formats to Germany; there are many other options for currency, numbers etc.
# for any other locale settings see: https://docs.python.org/3/library/locale.html

d = {'Time': [datetime(2020, k, 15) for k in range(2,7)],
      'value': np.random.rand(5)}
df=pd.DataFrame(d)
print(df)
print(df.info())
print(df["Time"].dt.strftime("%a %H:%M"))

#fig = px.line(df, y="value", x="Time")
# Update
fig = go.Figure(go.Scatter(mode='lines', x=[d.strftime('%a\n%H:%M') for d in df['Time']], y=df['value']))
#fig.update_xaxes(tickformat="%a\n%H:%M",)
fig.show()


0
投票

此问题的大多数解决方案建议将绘图的日期数据转换为字符串数据。在某些情况下,将时间轴转换为文本标签轴实际上并不起作用,因为它会丢失有关日期之间正确间距的信息,特别是如果您的日期间隔不均匀。 从版本 5.14 开始,您可以做的是使用 labelalias
属性来操作 Plotly 生成的轴标签。您可以在此处查看

我的其他答案
,了解一个小示例。

© www.soinside.com 2019 - 2024. All rights reserved.