【问题标题】:pandas histogram with logarithmic axes带有对数轴的 pandas 直方图
【发布时间】:2016-10-17 21:10:22
【问题描述】:

我有一个以秒为单位的时间长度数据的 pandas DataFrame。长度从几秒到几个月不等,因此在获取日志后获取直方图很方便,因为它可以更好地覆盖范围。这是一个示例代码

%matplotlib inline
import numpy as np
import pandas as pd

x=np.random.lognormal(mean=10, sigma=1, size=10000)
df=pd.DataFrame(x, range(10000), columns=['timeLength'])

np.log10(df.timeLength).hist()

但是,x 轴上的标签是对数缩放的。有没有办法将它们设置为 10^1 等等。或者更好,如果我可以将它们设置为 1 秒、10 秒、1 分钟、10 分钟、1 小时、1 天等等。

【问题讨论】:

    标签: python numpy pandas histogram


    【解决方案1】:

    如果您想使用自定义 bin,您可能需要将 pd.cut.groupby().count() 结合使用并使用 bar 图表:

    x=np.random.lognormal(mean=10, sigma=1, size=10000)
    df=pd.DataFrame(x, range(10000), columns=['timeLength'])
    
    df['bin'] = pd.cut(df.timeLength,include_lowest=True, bins=[0, 1, 10, 60, 60**2, 60**2*24, df.timeLength.max()], labels=['1s', '10s', '1min', '1hr', '1d', '>1d'])
    df.groupby('bin').count().plot.bar()
    

    【讨论】:

      【解决方案2】:

      非均匀 Bin 直方图

      而不是记录值,

      np.log10(df.timeLength)
      

      在计算直方图时尝试创建非均匀分箱。这可以通过np.histogram's bins argument 来完成。

      基于

      如果我可以将它们设为 1 秒、10 秒、1 分钟、10 分钟、1 小时、1 天等等。

      可以创建以下 bin 数组

      # Bin locations (time in seconds)
      bins = np.array([0, 1, 10, 60, 60*10, 60*60, 24*60*60])
      

      示例

      原始数据集被放大以填充更多的 bin(mean=5, sigma=2 而不是 mean=10, sigma=1),这仅是示例。定义非均匀箱,计算直方图并显示绘图。例如,这些垃圾箱可能会被更改。

      # Create random data in DataFrame
      x = np.random.lognormal(mean=5, sigma=2, size=10000)
      df = pd.DataFrame(x, columns=['timeLength'])
      
      print df.describe()
      print
      
      # Create non-uniform bins.  Unit in seconds.
      bins = np.array([0, 1, 10, 60, 60*10, 60*60, 24*60*60])
      print 'hisogram bins:', bins
      
      # Get histogram of random data
      y, x = np.histogram(df, bins=bins, normed=True)
      
      # Correct bin placement
      x = x[1:]
      
      # Turn into pandas Series
      hist = pd.Series(y, x)
      
      # Plot
      ax = hist.plot(kind='bar', width=1, alpha=0.5, align='center')
      ax.set_title('Non-Uniform Bin Histogram')
      ax.set_xlabel('Time Length')
      ax.set_xticklabels(['1 s', '10 s', '1 Min', '1 Hr', '1 Day', '>1 Day'], rotation='horizontal')
      

          timeLength   
      count   10000.000000
      mean     1014.865417
      std      4751.820312
      min         0.062893
      25%        36.941388
      50%       144.081235
      75%       556.223797
      max    237838.467337
      
      hisogram bins: [    0     1    10    60   600  3600 86400]
      

      如果这不是预期的结果,请告知。

      【讨论】:

      • 这正是我感兴趣的。感谢您提供的详细信息!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      • 2013-01-12
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 2018-11-25
      相关资源
      最近更新 更多