Vertical Histogram in Python and Matplotlib

29,497

Solution 1

Use orientation="horizontal" in ax.hist:

from matplotlib import pyplot as plt
import numpy as np

sample = np.random.normal(size=10000)

vert_hist = np.histogram(sample, bins=30)
ax1 = plt.subplot(2, 1, 1)
ax1.plot(vert_hist[0], vert_hist[1][:-1], '*g')

ax2 = plt.subplot(2, 1, 2)
ax2.hist(sample, bins=30, orientation="horizontal");
plt.show()

enter image description here

Solution 2

Just use barh() for the plot:

import math
from matplotlib import pyplot as plt
import numpy as np
sample=np.random.normal(size=10000)
vert_hist=np.histogram(sample,bins=30)

# Compute height of plot.
height = math.ceil(max(vert_hist[1])) - math.floor(min(vert_hist[1]))

# Compute height of each horizontal bar.
height = height/len(vert_hist[0])

ax1=plt.subplot(2,1,1)
ax1.barh(vert_hist[1][:-1],vert_hist[0], height=height)

ax2=plt.subplot(2,1,2)
ax2.hist(sample,bins=30)
plt.show()

enter image description here

Share:
29,497
Cupitor
Author by

Cupitor

Updated on July 12, 2020

Comments

  • Cupitor
    Cupitor almost 4 years

    How can I make a vertical histogram. Is there any option for that or should it be built from the scratch? What I want is the upper graph to look like the below one but on vertical axis!

    from matplotlib import pyplot as plt
    import numpy as np
    sample=np.random.normal(size=10000)
    vert_hist=np.histogram(sample,bins=30)
    ax1=plt.subplot(2,1,1)
    ax1.plot(vert_hist[0],vert_hist[1][:-1],'*g')
    
    ax2=plt.subplot(2,1,2)
    ax2.hist(sample,bins=30)
    plt.show()
    

    enter image description here