问题
我有 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
,然后类似于链接的线程,循环子图,创建一个twinx
和 lineplot
第二个 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('')
输出:
关于python - 将第二个 y 轴引入具有多个绘图的 relplot() 调用中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71070497/