【发布时间】:2022-09-30 03:40:50
【问题描述】:
问题
我有 2 个数据框,我将它们组合起来,然后与熊猫融为一体。我需要对它们进行多重绘制(如下所示),并且代码需要可扩展。它们包括2 个变量它形成了下面的 \'key\' 列(这里是 \'x\' 和 \'y\'),横跨多个\'站\'(这里只有 2 个,但需要可扩展)。我已经使用relplot() 能够在每个图表上多绘制两个变量,并在单独的图表上绘制不同的站点。
有什么方法可以保持这种格式,但在每个绘图中引入第二个 y 轴? \'x\' 和 \'y\' 需要在我的实际数据中处于不同的比例。我见过examples,其中relplot 调用与y = 1st variable 一起存储,并且为第二个变量添加了第二个lineplot 调用,其中包含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()
标签: python pandas matplotlib seaborn relplot