Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn plot with second y axis

i wanted to know how to make a plot with two y-axis so that my plot that looks like this : enter image description here

to something more like this by adding another y-axis : enter image description here

i'm only using this line of code from my plot in order to get the top 10 EngineVersions from my data frame :

sns.countplot(x='EngineVersion', data=train, order=train.EngineVersion.value_counts().iloc[:10].index);
like image 598
CHADTO Avatar asked Apr 12 '19 15:04

CHADTO


People also ask

How do you make a plot with two Y-axis in Python?

The easiest way to create a Matplotlib plot with two y axes is to use the twinx() function.

How do you set the Y-axis range in Seaborn?

Load the dataset using load_dataset("tips"); need Internet. Using boxplot(), draw a box plot to show distributions with respect to categories. To set the range of Y-axis, use the ylim() method. To display the figure, use the show() method.


2 Answers

I think you are looking for something like:

import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [1000,2000,500,8000,3000]
y1 = [1050,3000,2000,4000,6000]

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.bar(x, y)
ax2.plot(x, y1, 'o-', color="red" )

ax1.set_xlabel('X data')
ax1.set_ylabel('Counts', color='g')
ax2.set_ylabel('Detection Rates', color='b')

plt.show()

Output:

enter image description here

like image 112
BetaDev Avatar answered Oct 22 '22 00:10

BetaDev


@gdubs If you want to do this with Seaborn's library, this code set up worked for me. Instead of setting the ax assignment "outside" of the plot function in matplotlib, you do it "inside" of the plot function in Seaborn, where ax is the variable that stores the plot.

import seaborn as sns # Calls in seaborn

# These lines generate the data to be plotted
x = [1,2,3,4,5]
y = [1000,2000,500,8000,3000]
y1 = [1050,3000,2000,4000,6000]

fig, ax1 = plt.subplots() # initializes figure and plots

ax2 = ax1.twinx() # applies twinx to ax2, which is the second y axis. 

sns.barplot(x = x, y = y, ax = ax1, color = 'blue') # plots the first set of data, and sets it to ax1. 
sns.lineplot(x = x, y = y1, marker = 'o', color = 'red', ax = ax2) # plots the second set, and sets to ax2. 

# these lines add the annotations for the plot. 
ax1.set_xlabel('X data')
ax1.set_ylabel('Counts', color='g')
ax2.set_ylabel('Detection Rates', color='b')

plt.show(); # shows the plot. 

Output: Seaborn output example

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

rcsegura