简体   繁体   中英

Plotly: How to format date in hoverinfo when using plotly express line?

I am using following code to display time-series data using 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()

But in the plot upon hover it displays date in the format: "Month, Year" ie it does not display day. But I want dates to be displayed in the following format: "Month day, year".

You can do so through the right combination of text and hovertemplate in:

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()

The reason why ser['text'] is so messy is that the resulting figure displays unique dates on the x-axis. And, since plotly.express works on tidy or long rather than wide data , the column containing your dates in your dataset will most likely not have unique date values.

Here's an example building on some financial time series data with different categories which is a perfect case for px.line :

在此处输入图像描述

Complete code with sample data:

# 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM