python - 如何在保持 y 值范围的同时结合两个 Seaborn 线图?

标签 python matplotlib seaborn

我想组合两个具有不同范围的数字,例如图

Figure One

该图是通过绘制两个图合成的。但是,我想立即使用seaborn 库。但现在它显示像

Figure Two .

如何使用seaborn或任何其他Python绘图库组合不同的y范围数字?

我也添加了我的 python 代码

import seaborn as sns
import numpy as np
with sns.axes_style('white'):
     ax = sns.lineplot(x='unit_step', y='accuracy', hue='data_type', style='data_type', markers=True, dashes=True, data=data)
     ax.set_xticks(np.arange(1,6))

最佳答案

据我了解,您的问题是关于如何将两个范围截然不同的数据集绘制到一个子图中的请求,这里有一些提示您如何实现这一目标。

tl;dr:最后你只需要把 plt.twinx() 放在 plt.plot() 命令之前,该命令应该有一个辅助 y 轴。

首先假设两个函数,它们在同一定义范围内具有非常不同的值范围,f(x) = x³f(x) = sin(x) :

x = np.linspace(-2*np.pi, 2*np.pi, 100)
y1 = x**3
y2 = np.sin(x)

可以这样绘制:

fig, axs= plt.subplots(1, 2, figsize=(12, 6))

axs[0].plot(x, y1, 'b', x, y2, 'r')
axs[0].set_xlabel('X')
axs[0].set_ylabel('Y')

axs[1].plot(x, y1, 'b')
axs[1].set_xlabel('X')
axs[1].set_ylabel('Y1')

axs_sec = axs[1].twinx()        # <--- create secondary y-axis
axs_sec.plot(x, y2, 'r')
axs_sec.set_ylabel('Y2')

enter image description here

在左侧,您可以看到,如果绘制到同一 y 轴,则正弦几乎是不可见的。 在右侧,正弦被绘制到辅助 y 轴上,以便它有自己的缩放比例。

关于python - 如何在保持 y 值范围的同时结合两个 Seaborn 线图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52982277/

相关文章:

python - 跨多个用户的 RESTful API

python - 使用 pandas 将两个 Excel 表与 Python 连接起来

python - 如何实例化一个for循环x次

python - 通过命令行python批量上传视频到youtube

python - 按 matplotlib 中的列表值对条形图进行排序

python - 绘制二维数据 : heatmap with different colormaps

python - 如何在seaborn fiddle 图上使用箱线图的 mustache 参数?

python - 如何将 sympy 函数转换为使用 matplotlib 绘图?

pandas - Seaborn 热图颜色反转

python - Seaborn 情节未显示