Plotly: How to remove the empty gap on x-axis

◇◆丶佛笑我妖孽 提交于 2021-02-10 20:33:27

问题


I have done this diagram on plotly

And I want to delete the empty gap, to display only the x that have a value, and to hide the x where there isn't any value

How am I supposed to do that ?

Here is my code :

go.Bar(name=i,x=listeDepartement,y=listePPA))
fig = go.Figure(data=bar)
fig.update_layout(barmode='stack')
fig.write_html('histogram.html',auto_open=True)
fig.show()

回答1:


The reason why this happens is that plotly interprets your x-axis as dates, and makes a timeline for you. You can avoid this in several ways. One possibility is to replace the dates with string representations of dates.

Plot with dates on the x-axis:

Now, just replace x=df.index with x=df.index.strftime("%Y/%m/%d") in the snippet below to get this plot:

Plot with strings on the x-axis:

Code:

# imports
from plotly.subplots import make_subplots
import plotly.graph_objs as go
import pandas as pd
import numpy as np

# data
np.random.seed(123)
frame_rows = 50
n_plots = 1
frame_columns = ['V_'+str(e) for e in list(range(n_plots+1))]
df = pd.DataFrame(np.random.uniform(-10,10,size=(frame_rows, len(frame_columns))),
                  index=pd.date_range('1/1/2020', periods=frame_rows),
                    columns=frame_columns)
df=abs(df)
df.iloc[21:-2]=np.nan
df=df.dropna()

# show figure
fig = go.Figure()
fig.add_traces(go.Bar(#x=df.index,
                       x=df.index.strftime("%Y/%m/%d"),
                         y=df['V_0']))

fig.show()



回答2:


In case, someone is here playing with stocks data, Below is the code to hide outside trading hours and weekends with rangebreaks.

    fig = go.Figure(data=[go.Candlestick(x=df['date'], open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'])])
    fig.update_xaxes(
        rangeslider_visible=True,
        rangebreaks=[
            # NOTE: Below values are bound (not single values), ie. hide x to y
            dict(bounds=["sat", "mon"]),  # hide weekends, eg. hide sat to before mon
            dict(bounds=[16, 9.5], pattern="hour"),  # hide hours outside of 9.30am-4pm
            # dict(values=["2020-12-25", "2021-01-01"])  # hide holidays (Christmas and New Year's, etc)
        ]
    )
    fig.update_layout(
        title='Stock Analysis',
        yaxis_title=f'{symbol} Stock'
    )

    fig.show()

here's Plotly's doc.



来源:https://stackoverflow.com/questions/59021060/plotly-how-to-remove-the-empty-gap-on-x-axis

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