python - Plotly:使用 plotly express line 时如何在 hoverinfo 中格式化日期?

标签 python plotly data-visualization plotly-express

我正在使用以下代码使用 plotly express line 显示时间序列数据。

fig = px.line(df, x="date", y="close", color="type" ,category_orders = co ,color_discrete_sequence = colors,
              line_group="type", title = company)

fig.update_layout(height=500, width=1500)#hovermode="x unified"
fig.show()

但是在悬停时的图中,它以以下格式显示日期:“月,年”,即它不显示日。但我希望日期以下列格式显示:“月、日、年”。

最佳答案

您可以通过 texthovertemplate 的正确组合来做到这一点:

for ser in fig['data']:
    ser['text']=list(set([d.strftime('%Y-%m-%d') for d in df['dates']]))
    ser['hovertemplate']='category=open<br>dates=%{text}<br>price=%{y}<extra></extra>'
fig.show()

ser['text'] 如此困惑的原因是生成的图形在 x 轴上显示唯一 日期。而且,由于 plotly.express 适用于 tidy 或 long rather than wide data ,数据集中包含日期的列很可能具有唯一的日期值。

这是一个基于一些具有不同类别的金融时间序列数据的示例,它是 px.line 的完美案例:

enter image description here

带有示例数据的完整代码:

# imports
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime
import plotly.express as px

# data
open_data = [33.0, 33.3, 33.5, 33.0, 34.1]
high_data = [33.1, 33.3, 33.6, 33.2, 34.8]
low_data = [32.7, 32.7, 32.8, 32.6, 32.8]
close_data = [33.0, 32.9, 33.3, 33.1, 33.1]
dates = [datetime(year=2020, month=10, day=10),
         datetime(year=2020, month=10, day=11),
         datetime(year=2020, month=10, day=12),
         datetime(year=2020, month=10, day=13),
         datetime(year=2020, month=10, day=14)]

# data organized in a pandas dataframe
df=pd.DataFrame(dict(open=open_data,
                    high=high_data,
                    low=low_data,
                    close=close_data,
                    dates=dates))

# transform the data from wide to long
df = pd.melt(df, id_vars=['dates'], value_vars=df.columns[:-1],
         var_name='category', value_name = 'price')

# setup for a perfect plotly time series figure
fig = px.line(df, x="dates", y="price", title='Prices', color = 'category')

# edit text and hovertemplate
for ser in fig['data']:
    ser['text']=list(set([d.strftime('%Y-%m-%d') for d in df['dates']]))
    ser['hovertemplate']='category=open<br>dates=%{text}<br>price=%{y}<extra></extra>'

fig.show()

关于python - Plotly:使用 plotly express line 时如何在 hoverinfo 中格式化日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61459961/

相关文章:

应用程序中嵌入的 Python 解释器无法加载 native 模块

python - 将 json 转换为 SQLAlchemy 对象的更好方法

python - 如何在悬停文本 Plotly 中打破长行?

python - 尝试重用 RNN 权重时出错

matplotlib - 将 2D 图像 "projecting information"的 3D 图形相互叠加

pythonplotly-旋转辅助X轴标签

r - 如何在 R 中创建一个 'stacked waterfall' 图表?

python - 如何可视化 Pandas Dataframe 中的时间数据?

javascript - 我在 React 中使用 d3.js 创建了一个折线图。需要对其进行一些自定义,但不知道该怎么做。请看说明和代码

python - 在数据框中的每一行之后添加计算行