'Plotly Python format Time Axis to HH:MM issues
I tried many things, but the X-axis on plotly, which contains times in the format of HH:MM:SS in a pandas dataframe doesn't want to change.
I tried the following:
- Trying to change the datatype of the dataframe column to pydatetime
- adding the pydates to a list and applying strftime with '%Y-%m-%d %H:%M:%S' (to convert it later) and '%H:%M:%S'
- tried the basic stuff with tickformat="%H:%M" in fig.update_xaxes - Method
- and tickformat='%H:%M' in fig.update_layout - Method (also with dictionary) for xaxis parameter
- also tried this: fig.layout['xaxis_tickformat'] = "%H:%M"
- also tried to apply the dates to strftime with "%H:%M" but the values are a type of aggregated than (or only one value for the certain minute is picked)
The results change: Sometimes all datapoints disappear (they are on the left or right corner) and if they not disappear, the x-axis shows the values for 15:23:01 for example.
Below is a code snippet of my method:
pd.options.plotting.backend = "plotly"
dates = pd.to_datetime(dataframe.Time, format='%H:%M:%S')
dates = dates.dt.to_pydatetime()
datelist = []
for date in dates:
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S')
datelist.append(date)
# dates['Time'] = pd.Series(dates, dtype=object)
# dates = dates.apply(lambda x: x.strftime('%H:%M:%S'))
print(dataframe.Time)
print(dates)
df = dataframe
# also tried here with x = dataframe.Time with same results
fig = px.line(df, x=datelist, y=["Foo1", "Foo2"], title='Foo')
# changing Y-Axis ticks to 10 minutes
fig.update_xaxes(tickangle=45,
# type="date",
tickmode='array',
tickformat="%H:%M",
tickvals=df["Time"][0::600])
fig.update_layout(
title="Foo", title_x=0.5,
xaxis_title="Time",
xaxis=dict(
tickformat='%H:%M'
),
# xaxis_tickformat = "%H:%M",
yaxis_title="<i>g</i>",
legend_title="Sensor",
font=dict(
family="Courier New, monospace",
size=50,
color="RebeccaPurple"
)
)
# fig.layout['xaxis_tickformat'] = "%H:%M"
fig.show()
I hope you can help me as I followed the instructions on the plotly website and googled, but plotly stuff seems to be rare.
Thanks in advice, I can provide more infos if needed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
