Slartibartfast
Slartibartfast

Reputation: 1190

Plotting Multiple Scales on the same plot

I have the following code:

import pandas as pd
from pandas_datareader import data as web
import matplotlib as plt
import datetime as date

start = date.datetime(2000,1,1)
end = date.datetime.today()
df = web.DataReader('fb', 'yahoo',start, end)
df2  = web.DataReader('f', 'yahoo',start, end)

ax = df.plot(y = 'Close')

df3 = df2.pct_change()
df3.plot(y = 'Close', ax=ax)

This code produces the following chart:

enter image description here

The orange line is of a plot where it is percentage change thus it is plotted as a horizontal line.

Is it possible to plot percentage change on the same plot where i have plotted another symbol against price. What i had in mind was so that on the right axis it would show the percentage and on the left it would be the price. Is it possible ? If so could you please show me how?

Upvotes: 0

Views: 127

Answers (1)

Hugolmn
Hugolmn

Reputation: 1560

Just a little change : you need to use plt.subplots() as well as twinx. This way, the x-axis will be duplicated from ax, and use the other side of the plot for the y-axis

fig, ax = plt.subplots()
df.plot(y = 'Close', ax=ax)

ax2 = ax.twinx()
df3 = df2.pct_change()
df3.plot(y = 'Close', ax=ax2)

You will probably need to add a color argument, as both plots will use the same default color.

Upvotes: 1

Related Questions