Skip to content

Instantly share code, notes, and snippets.

@ksv-muralidhar
Last active September 24, 2021 09:59
Show Gist options
  • Save ksv-muralidhar/44aeae286c92e98e1feeeab9ff0be082 to your computer and use it in GitHub Desktop.
Save ksv-muralidhar/44aeae286c92e98e1feeeab9ff0be082 to your computer and use it in GitHub Desktop.
dual_axis
import pandas as pd
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(12,5))
ax2 = ax.twinx()
ax.set_title('GDP per capita ($) and GDP growth rate')
ax.set_xlabel('Year')
ax.plot(gdp['date'], gdp[' GDP Per Capita (US $)'], color='green', marker='x')
ax2.plot(gdp['date'], gdp[' Annual Growth Rate (%)'], color='red', marker='o')
ax.set_ylabel('GDP Per Capita (US $)')
ax2.set_ylabel('Annual Growth Rate (%)')
ax.legend(['GDP Per Capita (US $)'])
ax2.legend(['Annual Growth Rate (%)'], loc='upper center')
ax.set_xticks(gdp['date'].dt.date)
ax.set_xticklabels(gdp['date'].dt.year, rotation=90)
ax.yaxis.grid(color='lightgray', linestyle='dashed')
plt.tight_layout()
plt.show()
nifty = pd.read_csv('nifty.csv',
usecols=['Date', 'Close', 'Volume'])
nifty['Date'] = pd.to_datetime(nifty['Date'])
nifty_2021 = nifty.loc[nifty['Date'] >= '2021-07-01'].copy()
nifty_2021['Volume'] = nifty_2021['Volume']/1000
fig, ax = plt.subplots(figsize=(12,5))
ax.set_title('Nifty')
ax2 = ax.twinx()
nifty_2021.plot(x='Date', y='Volume', kind='bar', ax=ax, alpha=0.2, color='black')
ax.set_xticklabels(nifty_2021['Date'].dt.date, fontsize=8)
ax.get_legend().remove()
ax2.plot(ax.get_xticks(), nifty_2021['Close'], color='black')
ax.set_ylabel('Volume')
ax.set_yticks([0, 3000])
ax2.set_ylabel('Closing price')
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment