How to show timestamp x-axis in Python Plotly

橙三吉。 提交于 2020-05-17 07:52:49

问题


I want to plot this data to evaluate data availability. I used the following plotting code in Plotly.

import datetime
import plotly.express as px

fig = px.bar(df, x=df.index, y="variable", color='value', orientation="h",
             hover_data=[df.index],
             height=350,
             color_continuous_scale=['firebrick', '#2ca02c'],
             title='',
             template='plotly_white', 
            )

The result is just like what I want below.

But, the x-index show numbers. I want a timestamp (month+year) on the x-axis, instead.

Edit Adding the fllowing

fig.update_layout(yaxis=dict(title=''), 
                  xaxis=dict(
                      title='Timestamp', 
                      tickformat = '%Y-%b',
                  )
                 )

Gives

which seems that the x-axis is not read from the data index.


回答1:


If you want to use bars it seems to me that you need to find a nice workaround. Have you considered to use Heatmap?


import pandas as pd
import plotly.graph_objs as go

df = pd.read_csv("availability3.txt",
                 parse_dates=["Timestamp"])\
       .drop("Unnamed: 0", axis=1)

# you want to have variable as columns
df = pd.pivot_table(df,
                    index="Timestamp",
                    columns="variable",
                    values="value")
fig = go.Figure()
fig.add_trace(
    go.Heatmap(
        z=df.values.T,
        x=df.index,
        y=df.columns,
        colorscale='RdYlGn',
        xgap=1,
        ygap=2)
      )

fig.show()



来源:https://stackoverflow.com/questions/60098350/how-to-show-timestamp-x-axis-in-python-plotly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!