0

I have this code that is supposed to output a figure with 2 subplots with shape (2,1). 2 Pandas DataFrames that share the same index but different columns are used to plot the subplots by sharing the X-Axis for the index and plotting each column with different color.

## Create a  new figure with 2 subplots
fig1, _ = plt.subplots(2, 1, figsize = [10, 15]) 
## Select the upper subplot
plt.subplot(2, 1, 1)
## Plot the first DataFrame
ax1 = df1.plot(grid=True, sharex=True, title='Some Title', legend=True)
ax1.set_ylim(0,1)
plt.ylabel('Win Probabilites')
plt.legend(title="Risk Reward Ratios", fancybox=True)

## Select the lower subplot
plt.subplot(2, 1, 2)
## Plot the second DataFrame
df2.plot(grid=True, sharex=True, legend=True)
plt.ylabel('Expexted Returns')
plt.legend(title="Risk Reward Ratios", fancybox=True)

plt.savefig('fig.png')

The output should be something like this but with more lines of different colors for the other columns in each subplot: enter image description here The problem is that it only works when I select only one column from both data frames, i.e it only works with these modifications:

ax1 = df1['col'].plot(grid=True, sharex=True, title='Some Title', legend=True)

and

df2['col'].plot(grid=True, sharex=True, legend=True)

Without selecting single columns it outputs only the lower subplot.

I'm stuck and can't figure out what's wrong ..

  • 2
    Much better to use the object-oriented interface throughout. So, `fig1, (ax1, ax2) = plt.subplots(2, 1, figsize = [10, 15])`, then you can directly tell `df.plot` which Axes instance to plot on: `df1.plot(ax=ax1, ...)`, `df2.plot(ax=ax2, ...)` – tmdavison Sep 10 '21 at 08:48
  • Hello, would you mind posting some sample data. It is not possible to identify the problem without them. – Mohammad Sep 10 '21 at 08:49
  • 1
    If you use the OOA above, you can also then use `ax1.set_ylabel()` instead of `plt.ylabel` and `ax1.legend()` instead of `plt.legend()` – tmdavison Sep 10 '21 at 08:49
  • Thank a lot @tmdavison that actually worked perfectly! – Abdullah Bahi Sep 10 '21 at 09:13
  • 1
    The second part of this [answer]](https://stackoverflow.com/a/68793513/7758804) is probably best for this question. – Trenton McKinney Sep 10 '21 at 14:11

0 Answers0