Grisuu
Grisuu

Reputation: 109

Seaborn - Move x axis to top

I am plotting the following data set.

data = {'Surface':[0, -50, -100, -250, -600], 'Left':[0, 0, 0, 10, 50], 'Front':[0, 0, 5, 15, 90]} 

This is a negative value dataset and therfore I am trying to move the x-axis to the top of the plot instead of the normal bottom axis.

The plot looks like this now:

enter image description here

The dataset and code below:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

# initialise dataframe 
data = {'Surface':[0, -50, -100, -250, -600], 'Left':[0, 0, 0, 10, 50], 'Front':[0, 0, 5, 15, 90]} 

# Creates pandas DataFrame. 
df = pd.DataFrame(data)

#Plotting
g = sns.PairGrid(df, y_vars=["Surface"], x_vars=["Left", "Front"], height=4)
g.map(plt.scatter, color=".3")
g.map(sns.lineplot)

#Move X Axis to top
g.invert_yaxis()
g.xaxis.set_ticks_position("top")

I know that there is an option in matplotlib, but trying it in seaborn it gives an error with

AttributeError: 'PairGrid' object has no attribute 'xaxis'

Upvotes: 3

Views: 7722

Answers (2)

Andrea
Andrea

Reputation: 3077

I'm not sure this is the cleanest way, but it works:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

# initialise dataframe 
data = {'Surface':[0, -50, -100, -250, -600], 'Left':[0, 0, 0, 10, 50], 'Front':[0, 0, 5, 15, 90]} 

# Creates pandas DataFrame. 
df = pd.DataFrame(data)

#Plotting
g = sns.PairGrid(df, y_vars=["Surface"], x_vars=["Left", "Front"], height=4)
g.map(plt.scatter, color=".3")
g.map(sns.lineplot)

#Move X Axis to top
g.axes[0][0].invert_yaxis()
for ax in g.axes[0]:
    ax.xaxis.tick_top()
    ax.xaxis.set_label_position('top')
    ax.spines['bottom'].set_visible(False)
    ax.spines['top'].set_visible(True)

enter image description here

Upvotes: 0

CAPSLOCK
CAPSLOCK

Reputation: 6483

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

# initialise dataframe 
data = {'Surface':[0, -50, -100, -250, -600], 'Left':[0, 0, 0, 10, 50], 'Front':[0, 0, 5, 15, 90]} 

# Creates pandas DataFrame. 
df = pd.DataFrame(data)

#Plotting
g = sns.PairGrid(df, y_vars=["Surface"], x_vars=["Left", "Front"], height=4)
g.map(plt.scatter, color=".3")
g.map(sns.lineplot)

#Move X Axis to top
#g.invert_yaxis()
g.axes[0,1].xaxis.set_ticks_position("top")

g.axes[0,0].xaxis.set_ticks_position("top")

Upvotes: 3

Related Questions