在数据框的列中创建两个具有特定值的子图

问题描述 投票:0回答:1

我想在数据框的列中创建两个具有特定值的子图:

  • X轴是常见的ITows
  • Y 轴:电离值
  • 在第一个 Y 轴上,我想在 sourceId = 1 时绘制 ionocorr ,在另一个 Y 轴上,我想在 sourceId = 2 时绘制 ionocorr

我的数据如下所示:

我知道上面的代码只会在sourceId=1时绘制。但我想用上面提到的条件进行绘制。 以下是我尝试过的:

        df2 = final_df1.loc[final_df1['sourceId'] == 1.0]
        for data in df2.items():
            fig, (ax0, ax1) = plt.subplots(nrows=2, ncols=1, figsize=(8.27, 11.69))
            ax2 = ax0.twinx()
            ax0.plot(df2['iTOW'], df2['ionoCorr'], color="green")
            ax0.set_ylabel("Correction")
            ax0.set_xlabel("Itows")
            ax0.grid(True)
            ax0.set_title(input_file_path, wrap=True)
            ax2.set_ylabel('HPG Filter', color = 'b')
            pdf.savefig()
            plt.close()

任何指示都会有帮助。 另外,如果这可以在单个子图中(而不是两个)中实现,也会很有帮助

python-3.x dataframe matplotlib
1个回答
0
投票

您可以在两个子图或同一个图表上。这是两个例子,2 个子图:

import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv("test1a.csv")

fig, ax = plt.subplots(nrows=2, figsize=(8.27, 11.69))
for i, source_id in enumerate([1, 2]):
    mask = df["sourceId"] == source_id
    ax[i].plot(df[mask]['iTOW'], df[mask]['ionoCorr'], color="green")
    ax[i].set_ylabel("Correction")
    ax[i].set_xlabel("Itows")
    ax[i].set_title(f"Source {source_id}")
    ax[i].grid(True)

和单个情节:

import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv("test1a.csv")

fig, ax = plt.subplots()
for i, (source_id, color) in enumerate([(1, "green"), (2, "red")]):
    mask = df["sourceId"] == source_id
    ax.plot(df[mask]['iTOW'], df[mask]['ionoCorr'], color=color, label=f"Source {source_id}")

ax.set_ylabel("Correction")
ax.set_xlabel("Itows")
ax.grid(True)
ax.legend()

© www.soinside.com 2019 - 2024. All rights reserved.