【问题标题】:Plotly: How to plot histogram in Root style showing only the contours of the histogram?Plotly:如何以 Root 样式绘制直方图,仅显示直方图的轮廓?
【发布时间】:2021-11-23 00:23:21
【问题描述】:

我想用这种风格制作直方图:

但是在 Python 中使用 plotly。 IE。我想合并条形图并仅绘制轮廓。我正在使用此代码:

import plotly.graph_objects as go

import numpy as np

x = np.random.randn(500)
fig = go.Figure(data=[go.Histogram(x=x)])
fig.show()

我一直在寻找有关如何执行此操作的示例,但找不到任何示例。

【问题讨论】:

    标签: python plotly histogram plotly-python


    【解决方案1】:
    import plotly.graph_objects as go
    import numpy as np
    import pandas as pd
    
    x = np.random.randn(100)
    
    # build data frame that is histogram
    df = pd.cut(x, bins=10).value_counts().to_frame().assign(
        l=lambda d: pd.IntervalIndex(d.index).left,
        r=lambda d: pd.IntervalIndex(d.index).right,
    ).sort_values(["l","r"]).rename(columns={0:"y"}).astype(float)
    
    # lines in plotly are delimited by none
    def line_array(df, cols):
        return np.pad(
            df.loc[:, cols].values, [(0, 0), (0, 1)], constant_values=None
        ).reshape(1, (len(df) * 3))[0]
    
    # plot just lines
    go.Figure(go.Scatter(x=line_array(df, ["l","r"]), y=line_array(df, ["y","y"]), marker={"color":"black"}))
    

    【讨论】:

      【解决方案2】:

      您最好的选择是使用像count, index = np.histogram(df['data'], bins=25) 这样的numpy 处理直方图,然后使用go.Scatter() 并将线型设置为horizontal, vertical, horizontalline=dict(width = 1, shape='hvh')。看看最后一节为什么go.Histogram() 不是您的最佳选择。加上go.Scatter() 的布局的其他一些规范,下面的 sn-p 将产生以下图:

      完整代码

      import plotly.graph_objects as go
      import pandas as pd
      import numpy as np
      import plotly.io as pio
      import plotly.express as px
      
      pio.templates.default = "plotly_white"
      
      # random numbers to a df
      np.random.seed(12)
      df = pd.DataFrame({'data': np.random.randn(500)})
      
      # produce histogram data wiht numpy
      count, index = np.histogram(df['data'], bins=25)
      
      # plotly, go.Scatter with line shape set to 'hvh'
      fig = go.Figure()
      fig.add_traces(go.Scatter(x=index, y = count,
                                line=dict(width = 1, shape='hvh')))
      
      # y-axis cosmetics
      fig.update_yaxes(
          showgrid=False,
          ticks="inside",
          tickson="boundaries",
          ticklen=10,
          showline=True,
          linewidth=1,
          linecolor='black',
          mirror=True,
          zeroline=False)
      
      # x-axis cosmetics
      fig.update_xaxes(
          showgrid=False,
          ticks="inside",
          tickson="boundaries",
          ticklen=10,
          showline=True,
          linewidth=1,
          linecolor='black',
          mirror=True,
          zeroline=False)
      
      fig.show()
      

      为什么是go.Scatter() 而不是go.Histogram()

      使用fig = go.Figure(data=[go.Histogram(x=x)]) 的方法最接近您想要的情节是这样的:

      这非常接近,但您特别想排除每个“条”的垂直线。而且我还没有找到使用go.Histogram 设置排除或隐藏它们的方法。

      go.Histogram() 的代码

      import plotly.graph_objects as go
      import pandas as pd
      import numpy as np
      import plotly.io as pio
      import plotly.express as px
      
      pio.templates.default = "plotly_white"
      
      import numpy as np
      
      x = np.random.randn(500)
      fig = go.Figure(data=[go.Histogram(x=x)])
      fig.update_traces(marker=dict(color='rgba(0,0,0,0)', line=dict(width=1, color='blue')))
      fig.show()
      

      【讨论】:

      • 哇,这么好的答案。我会给你不止一个“向上箭头”。谢谢!
      猜你喜欢
      • 2018-01-06
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多