sol*_*sol 5 python matplotlib seaborn
我搜索使用seaborn和y轴损坏的小提琴图绘制catplot(因为我有一个作用在两个不同尺度上的因果过程:一个在[0,0.2]之间,第二个在[2,12]之间定量 y 变量)。
我从这个答案中了解到,还没有实现允许在seaborn中进行这种绘图的简单功能(还?) 所以我尝试了不同的方法,但没有成功,堆叠同一数据集但具有两种不同比例的两个图。
探索失败的尝试:
让我们使用标准数据集“exercise”,我尝试过:
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
exercise = sns.load_dataset("exercise")
f, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, sharey=True)
f = sns.catplot(x="time", y="pulse", hue="kind",data=exercise, kind="violin",ax=ax1)
f = sns.catplot(x="time", y="pulse", hue="kind",data=exercise, kind="violin",ax=ax2)
ax1.set_ylim(0, 6.5) # those limits are fake
ax2.set_ylim(13.5, 20)
plt.subplots_adjust(wspace=0, hspace=0)
plt.show()
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用facegrid但没有成功
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
exercise = sns.load_dataset("exercise")
g = sns.FacetGrid(exercise, col="kind",row="time")
g.map(sns.catplot, x="time", y="pulse", hue="kind",data=exercise, kind="violin")
plt.show()
Run Code Online (Sandbox Code Playgroud)
在这里,它为我提供了绘图网格的正确基础,但绘图发生在其他图中。
如果要在子图上绘图,则不能使用catplot,它是图形级函数。相反,您需要violinplot直接使用。sharey=True此外,如果您想要两个不同的 y 尺度,则在创建子图时无法使用。
其余部分几乎是从matplotlib 的断轴教程中复制/粘贴的
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
exercise = sns.load_dataset("exercise")
f, (ax_top, ax_bottom) = plt.subplots(ncols=1, nrows=2, sharex=True, gridspec_kw={'hspace':0.05})
sns.violinplot(x="time", y="pulse", hue="kind",data=exercise, ax=ax_top)
sns.violinplot(x="time", y="pulse", hue="kind",data=exercise, ax=ax_bottom)
ax_top.set_ylim(bottom=125) # those limits are fake
ax_bottom.set_ylim(0,100)
sns.despine(ax=ax_bottom)
sns.despine(ax=ax_top, bottom=True)
ax = ax_top
d = .015 # how big to make the diagonal lines in axes coordinates
# arguments to pass to plot, just so we don't keep repeating them
kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)
ax.plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal
ax2 = ax_bottom
kwargs.update(transform=ax2.transAxes) # switch to the bottom axes
ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal
#remove one of the legend
ax_bottom.legend_.remove()
plt.show()
Run Code Online (Sandbox Code Playgroud)