Last active
November 2, 2021 02:21
-
-
Save Thiagobc23/4ca2066f4f21fdd1c37ebaf9d264a920 to your computer and use it in GitHub Desktop.
Matplotlib line charts with secondary axis | dual-axis | double-axis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
import numpy as np | |
import pandas as pd | |
url = 'https://gist.githubusercontent.com/Thiagobc23/4ccb4ea1c612d9d68921bf990ce28855/raw/6225824a6b7d5d273019c09c25cbbaa5b82009bc/dummy_data.csv' | |
df = pd.read_csv(url, index_col='ID') | |
# figure | |
fig, ax = plt.subplots(1, figsize=(12,4), facecolor='#293952') | |
ax.set_facecolor('#293952') | |
# data | |
dt = df.Date | |
price = df['Price'] | |
rate = df['Exchange Rate'] | |
# plot | |
plt.plot(dt, price, marker='o', markersize=4, color='#FDAC53', linewidth=2.5) | |
ax2 = ax.twinx() | |
ax2.plot(dt, rate, marker='o', markersize=4, color='#55A380', linewidth=2.5) | |
# ticks | |
ax.tick_params(axis='both', colors='w') | |
ax2.tick_params(axis='both', colors='w') | |
plt.xticks(dt[::3]) | |
# spines | |
for i in ['top', 'bottom']: | |
ax.spines[i].set_visible(False) | |
ax2.spines[i].set_visible(False) | |
ax2.spines['left'].set_color('#FDAC53') | |
ax2.spines['left'].set_linewidth(2) | |
ax2.spines['right'].set_color('#55A380') | |
ax2.spines['right'].set_linewidth(2) | |
# grid | |
ax.set_axisbelow(True) | |
ax.xaxis.grid(color='w', linestyle='dashed', alpha=0.5) | |
# labels n title | |
ax.set_ylabel('Price', color='w', fontsize=12) | |
ax2.set_ylabel('Exchange Rate', color='w', fontsize=12) | |
plt.title('Price and Exchange Rate\n', loc='left', color='w', fontsize=16) | |
# limits | |
ax.set_ylim(0,) | |
ax2.set_ylim(0,) | |
plt.tight_layout() | |
#plt.show() | |
plt.savefig('secondary_axis.png', facecolor='#293952') |
Author
Thiagobc23
commented
Nov 2, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment