Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn BarPlot invert y axis and keep x axis on bottom of chart area

In Excel, I can take a graph that looks like this: enter image description here

And make it look like this:

enter image description here

By inverting the Y axis and setting "Horizontal Axis Crosses" to "max".

I would like to do this same thing in Seaborn. I can flip the y_axis using .invert_yaxis() but I am unable to keep the bars on the bottom of the chart like I can in Excel.

import seaborn as sns
barplot = sns.barplot(x='abc'
                      ,y='def'
                      ,data=df
                      ,ci=None
                      )
barplot.invert_yaxis()
barplot.figure

Which produces something like this: enter image description here

How can I move the bars from starting at the top, to starting at the bottom?

I am using Python 3.6 and seaborn 0.7.1

My question seems similar to this one but this question is unclear and has no answer: Pyplot - Invert Y labels without inverting bar chart

like image 638
BeeGee Avatar asked Jun 13 '17 22:06

BeeGee


People also ask

How do you invert axis in Seaborn?

The value of Y-axis in a seaborn heatmap is reversed when home icon or H button is pushed.

How do you invert the Y axis?

Flipping axis using the Format Axis dialog To do this, we have to right click the y axis that we want to reverse. Then, select the Format Axis from the context menu. The next thing to do is to check the Categories in reverse order. This is found in the Format Axis dialog, in the Axis Options.

How do you invert the Y axis in Python?

To invert Y-axis, we can use invert_yaxis() method. In the above example, we import the matplotlib. pyplot and numpy library.


2 Answers

seaborn.barplot is a wrapper for pyplot.bar and you may use pyplot.bar to create the plot with an inverted yaxis and bars that range from the bottom of the chart to a lower value up the y axis:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({"x":range(5), "y": [1,1.2,1.4,1.6,1.8]})

plt.bar(df.x, 2*np.ones(len(df))-df.y, bottom= df.y )
plt.gca().invert_yaxis()
plt.ylim(2,0)
plt.show()

enter image description here

like image 131
ImportanceOfBeingErnest Avatar answered Oct 21 '22 23:10

ImportanceOfBeingErnest


I found out that you can simply do:

plt.ylim(reversed(plt.ylim()))

which allows you to keep using Seaborn.

like image 24
Tanachat Avatar answered Oct 21 '22 21:10

Tanachat