【问题标题】:How can I break up this vertical binned histogram every n number of seconds?如何每隔 n 秒分解这个垂直分箱直方图?
【发布时间】:2021-08-22 16:53:41
【问题描述】:

我有一个包含 2 列的 CSV 文件:第一列是以秒为单位的时间,第二列是每第 n 秒从 -1 到 1 的值。我正在使用的文件的标题如下:

0,0.04408189999999999
1000,0.017673066666666678
2000,0.05512853333333334
3000,0.04731979999999998
4000,0.007375333333333322
5000,-0.0173186
6000,-0.030183500000000016
7000,-0.09746066666666667
8000,-0.11819146666666666
9000,-0.1189849333333333
10000,-0.10441406666666667
11000,-0.09025903333333336
12000,-0.14047866666666667
13000,-0.09634883333333336
14000,-0.09841593333333337
15000,-0.10307009999999997
16000,-0.08617349999999996
17000,-0.09265753333333335
18000,-0.11357536666666662
19000,-0.0669533666666667
20000,-0.05702283333333334
21000,-0.018528333333333317
22000,-0.0845192666666667
23000,-0.11929543333333334
24000,-0.12107416666666668

使用 python,我使用以下代码绘制了频率直方图:

data.iloc[:, 0:1:1].hist(bins=[-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, 
                               -0.4, -0.3, -0.2, -0.1, 0.0, 0.1, 
                                0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 
                                0.9, 1.0], 
           color='b', edgecolor='white', xlabelsize=8, ylabelsize=8, 
           grid=False, figsize=(10,8), orientation="horizontal")

生产者:

当前频率直方图显示所有时间的条形图。但是,我想在 t=100s、t=200s、t=300s 等处显示频率直方图……并将其显示在同一个图中,如下图:

如何在 python 中实现这一点?

【问题讨论】:

    标签: python matplotlib plot histogram bin


    【解决方案1】:

    据我所知,没有“开箱即用”的工具可以做到这一点。但是您可以使用移位轴来模拟这种行为。这通过使用双轴来工作,每个历史图都在其自己的轴上,其范围略微偏离前一个图。这些轴的刻度是隐藏的,原始(空)轴用于绘制“时间”变量。

    # dummy data
    df = pd.DataFrame({'time': np.random.randint(0,10, size=10000),
                       'value': np.random.normal(scale=0.3, size=10000)*2-1
                      })
    # plotting
    shift=1
    ax = plt.subplot()
    n = len(df['time'].unique())
    i = 0
    ax.set_xlim(0,n*shift)
    ax.set_xlabel('time group')
    for name,d in df.groupby('time'):
        ax2 = ax.twiny()
        ax2.set_xlim(-i*shift, (n-i)*shift)
        ax2.hist(d['value'], orientation='horizontal', density=True)
        ax2.xaxis.set_visible(False)
        i+=1
    

    输出:

    注意。我设置density=True 以确保每个hist 的宽度为1,但您可以使用计数,然后您需要将shift 增加到最大预期计数并重新标记“时间”轴

    【讨论】:

    • 太好了!当我遇到索引错误时,您将如何将两列数据传递给它?如,我想绘制完全相同的图,但使用我在问题中提供的数据。有什么想法吗?
    • 你试过ax2.hist(d[['value1, 'value 2']], ...)吗?
    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多