【问题标题】:Plotly: How to remove the empty gap on x-axisPlotly:如何去除 x 轴上的空白
【发布时间】:2019-11-24 18:33:45
【问题描述】:

我在 plotly 上做了这张图

我想删除空白,只显示有值的 x,并隐藏没有任何值的 x

我该怎么做?

这是我的代码:

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

【问题讨论】:

  • 我的建议对你有什么效果?

标签: python plotly axis diagram


【解决方案1】:

发生这种情况的原因是将您的 x 轴解释为日期,并为您制作时间表。您可以通过多种方式避免这种情况。一种可能性是将日期替换为日期的字符串表示形式。

在 x 轴上绘制日期:

现在,只需在下面的 sn-p 中将 x=df.index 替换为 x=df.index.strftime("%Y/%m/%d") 即可获得此图:

在 x 轴上绘制字符串:

代码:

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

【讨论】:

  • 然后您可以使用 strftime 语法格式化轴,使其看起来像 Ploty;例如 "%b %Y" 给出类似的缩写月份和 4 位数年份。
【解决方案2】:

如果有人在这里玩股票数据,下面是隐藏非交易时间周末的代码。

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

这里是Plotly's doc

【讨论】:

  • 由于某种原因,如果我使用dict(bounds=[11.5, 13], pattern="hour") 排除 11:30 和 13:00 之间的间隙,则图表变为空白。有什么想法吗?
猜你喜欢
  • 2020-09-05
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 2021-11-05
  • 1970-01-01
相关资源
最近更新 更多