Search code examples
pythonplotly

Flip left-right Plotly Horizontal Histogram


I've made a horizontal histogram as shown on the right in the image below. This can be done using the orientation kwyword in matplotlib's hist() function, as shown in the code below, which generates the following plot.

enter image description here

import numpy as np
import matplotlib.pyplot as plt

#generate some data
data = np.random.normal(size=100)

#define the plot
fig, ax = plt.subplots()

#plot the data as a histogram
ax.hist(data, orientation=u'horizontal')

#move ticks to the right
ax.yaxis.tick_right()

plt.show()

Is it possible to flip the x-axis, such that the base of the bars is on the right, and the bars extend out to the left, like the left hand plot in the image below?

enter image description here


Solution

  • The answer is simply to invert the order of the axis limit for the axis you wish to mirror. In this particular case, one can achieve the desired result like so:

    import numpy as np
    import matplotlib.pyplot as plt
    
    #generate some data
    data = np.random.normal(size=100)
    
    #define the plot
    fig, ax = plt.subplots()
    
    #plot the data as a histogram
    ax.hist(data, orientation=u'horizontal')
    
    #invert the order of x-axis values
    ax.set_xlim(ax.get_xlim()[::-1])
    
    #move ticks to the right
    ax.yaxis.tick_right()
    
    plt.show()