How do you set the axes on a histogram and swap the x and y axes?

TDJ92 picture TDJ92 · Sep 11, 2014 · Viewed 19.8k times · Source

I have a dataset where I want to plot a histogram of the number of measurements at each depth. I want to plot a histogram of each the frequency of measurements in the depth column. I want to bin the data into 5m chuncks starting at 0m, going up to 155m. This code, gets me a histogram, which looks a reasonable shape, but the values seem wrong, and I can't quite get it to start at 0. In addition, I would like to be able to swap the x-axis and y-axis, so that depth is on the y-axis, and frequency, is on the x-axis.

    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

The data is in this format:

TagID    ProfileNo   ProfileDirn     DateTime    Lat     Lon     Depth   Temperature

Answer

tacaswell picture tacaswell · Sep 13, 2014

You want the orientation kwarg of hist (Docs).

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

enter image description here