python - 将第二个 y 轴引入具有多个绘图的 relplot() 调用中

标签 python pandas matplotlib seaborn relplot

问题

我有 2 个数据框,我将它们组合起来,然后与 pandas 融为一体。我需要对它们进行多重绘制(如下所示)并且代码需要可扩展。它们由2个变量组成,形成下面的“关键”列(此处为“x”和“y”),跨越多个“站”(此处只有2个,但需要可扩展)。我用过relplot()能够在每个图表上多重绘制两个变量,并在单独的图表上绘制不同的站。

有什么方法可以保持这种格式,但在每个图中引入第二个 y 轴?在我的实际数据中,“x”和“y”需要具有不同的比例。我见过examples其中 relplot 调用存储为 y = 1st variable ,并为第二个变量添加第二个线图调用 ax.twinx()包含在其中。因此,在下面的示例中,“x”和“y”在同一个图表上各有一个 y 轴。

如何在“key”= 2 个变量且“station”长度为 n 的融化数据框(例如下面)中使用它?或者是废弃 df 格式并重新开始的答案?

示例代码

目前的多图:

import numpy as np
np.random.seed(123)
date_range = pd.period_range('1981-01-01','1981-01-04',freq='D')
x = np.random.randint(1, 10, (4,2))
y = np.random.randint(1, 10, (4,2))
x = pd.DataFrame(x, index = date_range, columns = ['station1','station2'])
y = pd.DataFrame(y, index = date_range + pd.to_timedelta(1, unit="D"), columns = ['station1','station2'])

#keep information where each data point comes from
x["key"], y["key"] = "x", "y"
#moving index into a column 
x = x.reset_index()
y = y.reset_index()
#and changing it to datetime values that seaborn can understand
#necessary because pd.Period data is used
x["index"] = pd.to_datetime(x["index"].astype(str))
y["index"] = pd.to_datetime(y["index"].astype(str))

#combining dataframes and reshaping 
df = pd.concat([x, y]).melt(["index", "key"], var_name="station", value_name="station_value")

#plotting
fg = sns.relplot(data=df, x = "index", y = "station_value", kind = "line", hue = "key", row = "station")

#shouldn't be necessary but this example had too many ticks for the interval
from matplotlib.dates import DateFormatter, DayLocator
fg.axes[0,0].xaxis.set_major_locator(DayLocator(interval=1))
fg.axes[0,0].xaxis.set_major_formatter(DateFormatter("%y-%m-%d"))

plt.show()

最佳答案

您可以仅对一个key(没有hue)进行relplot,然后类似于链接的线程,循环子图,创建一个twinxlineplot 第二个 key/station 组合:

#plotting
fg = sns.relplot(data=df[df['key']=='x'], x="index", y="station_value", kind="line", row="station")

for station, ax in fg.axes_dict.items():  
    ax1 = ax.twinx()
    sns.lineplot(data=df[(df['key'] == 'y') & (df['station'] == station)], x='index', y='station_value', color='orange', ci=None, ax=ax1)
    ax1.set_ylabel('')

输出:

enter image description here

关于python - 将第二个 y 轴引入具有多个绘图的 relplot() 调用中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71070497/

相关文章:

python - 由于数据帧错误,无法绘制实时数据

python - 在 Pycharm 中使用 raw_input 时出现 EOFError

python - 在 Python 表格中设置 x 轴频率

python - SQLAlchemy Unicode 难题

c# - 查询 Pandas 数据框

python - 在 Pandas 中将 DataFrame 名称保存为 .csv 文件名

python - 根据第二个数据帧的匹配列更新 pandas 数据帧

python - 如何在 matplotlib 中的曲线末端放置一个箭头?

Python-使用日期创建月份的周数列表

python - 使用 SQLAlchemy,如何在类中创建一个字段,该字段是该类的其他实例的列表?