How to flip axes on seaborn tsplot plot?

2019-09-14 03:20发布

问题:

I have data with various measurements and depth associated with those measurements. I am able to plot the data with the shaded error bounds as the y axis and depth as the x axis. However, I want the data with the error bounds to be on the x axis and depth on the y. Is there a way to tell tsplot to use the data parameter as the x axis and depth as the y or to flip the axes? Basically I want to turn this

into this

with all the proper axes formatting as it would if you simply transposed an array in matplotlib.

回答1:

The tsplot expects time on the horizontal axes. It's therefore not straight forward to transpose it. However we can get the respective data from a horizontal plot and use it to generate a vertical plot from the same data.

import numpy as np; np.random.seed(22)
import seaborn as sns
import matplotlib.pyplot as plt

X = np.linspace(0, 15, 31)
data = np.sin(X) + np.random.rand(10, 31) + np.random.randn(10, 1)

plt.figure(figsize=(4,6))
ax = sns.tsplot(time=X, data=data)
#get the line and the shape from the tsplot
x,y =ax.lines[0].get_data()
c = ax.collections[0].get_paths()[0].vertices
# discart the tsplot
ax.clear()

# create new plot on the axes, inverting x and y
ax.fill_between(c[:,1], c[:,0], alpha=0.5)
ax.plot(y,x)

plt.show()