【问题标题】:How do you set the axes on a histogram and swap the x and y axes?如何在直方图上设置轴并交换 x 和 y 轴?
【发布时间】:2014-09-11 10:17:13
【问题描述】:

我有一个数据集,我想在其中绘制每个深度处测量次数的直方图。我想在深度列中绘制每个测量频率的直方图。我想将数据分成 5m 块,从 0m 开始,一直到 155m。这段代码给我一个直方图,它看起来是一个合理的形状,但值似乎是错误的,我不能让它从 0 开始。此外,我希望能够交换 x 轴和 y - 轴,因此深度在 y 轴上,频率在 x 轴上。

    import numpy as np
    import datetime as dt
    import matplotlib.pyplot as plt
    import glob


    #The data is read in, and then formatted so that an array Dout (based on depth) is created. This is done since multiple files will be read into the code, and so I can create the histogram for all the files I have up until this point.

    Dout = np.array(depthout)


    bins = np.linspace(0, 130, num=13) #, endpoint=True, retstep=False)


    plt.hist(Dout, bins)
    plt.xlabel('Depth / m')
    plt.ylabel('Frequency')
    plt.show()


    # the end

数据格式如下:

TagID    ProfileNo   ProfileDirn     DateTime    Lat     Lon     Depth   Temperature

【问题讨论】:

  • 阅读标题后单击问题时,我预计会出现完全不同的代码块。也许您可以发布一个没有所有数据管理的最小示例,这更适合标题。对于水平条形图,请查看 matplotlib 库中的 barh_demo:matplotlib.org/gallery.html
  • 这听起来像是 pandas 包的完美工作。使用 pd.read_clipboard() 将您的代码放入数据框中。然后 df.Temperature.hist() 给你直方图。有很多切片选项可以用很少的代码做你想做的事情。
  • 这适用于多个文件吗?抱歉,我之前从未使用过 pandas。
  • @Nras 这样更好吗?该链接提供了必要的分箱信息!谢谢!但是,频率仍然肯定是错误的......

标签: python matplotlib histogram bin


【解决方案1】:

你想要 hist (Docs) 的 orientation kwarg。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

data = np.random.randn(1500)
bins = np.linspace(-5, 5, 25, endpoint=True)

ax.hist(data, bins, orientation='horizontal')
ax.set_ylim([-5, 5])
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 2021-10-24
    相关资源
    最近更新 更多