Reputation: 31
Let's say I've got a dataframe that looks like this (indexed on dates):
Value1 Value2 Value3 Value4 Value5
1 1 3 4 -1
2 2 3 4 1
3 3 3 2 -1
The values don't really matter, but I wanted to show an example.
I've got what seems like a fairly basic issue. I am trying to plot a MACD chart like the one found here. I want a plot that has the stock price with a plot immediately below it with the MACD lines. I've got subplots working, but I can't figure out how to get a linegraph and a barchart on the same chart. I've tried the following:
fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True, squeeze=False)
ind3.iloc[:,0].plot(title="Stock Price", ax=axes[0,0], fontsize=12, color=colors)
ind3.iloc[:,1:-1].plot(title="MACD", ax=axes[1,0], fontsize=12, color=colors)
ind3.iloc[:,-1].plot(title="MACD", ax=axes[1,0], kind='bar',fontsize=12, color=colors)
Which results in gibberish that looks like this:
Can anyone help? Thanks!
Upvotes: 1
Views: 503
Reputation: 10158
That is probably related to the way you're indexing using iloc
but its hard to tell without seeing the rest of your code.
Multiple plots in a subplot just requires you to call plot
/bar
on a specific subplot, and pass it the data you want to plot. In general, the structure looks something like this...
Generate some test data:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randint(0,100,size=(10,2)), columns=list('AB'))
df['time'] = pd.date_range('2019-03-01', periods=10, freq='1D')
df = df.set_index('time')
print(df)
A B
time
2019-03-01 12 73
2019-03-02 46 12
2019-03-03 41 10
2019-03-04 18 89
2019-03-05 60 98
2019-03-06 57 23
2019-03-07 59 73
2019-03-08 76 41
2019-03-09 71 34
2019-03-10 38 16
Create the plot:
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(8,10))
ax[0].set_title('Stock Price')
ax[1].set_title('MACD')
ax[1].plot(df.index, df['A'], color='b', label='Signal')
ax[1].bar(df.index, df['B'], color='g', label='MACD')
ax[1].set_xticklabels(df.index, rotation=90)
plt.legend(loc=1)
plt.tight_layout()
plt.show()
Upvotes: 1