Skip to content

Instantly share code, notes, and snippets.

@Thiagobc23
Last active October 28, 2021 03:14
Show Gist options
  • Save Thiagobc23/62ae396e96764135e47abf2dd755cfb3 to your computer and use it in GitHub Desktop.
Save Thiagobc23/62ae396e96764135e47abf2dd755cfb3 to your computer and use it in GitHub Desktop.
Smooth line chart with Matplotlib (scipy interpolate)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import interpolate
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
price = df['Price']
# interpolate
x = np.arange(0, len(price))
y = price
inter = interpolate.interp1d(x, y, kind = 'cubic')
new_x = np.arange(0, len(y)-1, 0.01)
new_y = inter(new_x)
# interpolated lines
plt.plot(new_x, new_y, color='#FDAC53', linewidth=1.5)
# data points
plt.scatter(x, price, color='#FDAC53', s=15, zorder=3)
# ticks and title
ax.tick_params(axis='both', colors='w')
plt.xticks(x[::3], df.Date[::3])
plt.title('Price\n', loc='left', color='w', fontsize=16)
# spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_color('w')
ax.spines['bottom'].set_color('w')
# grid
ax.set_axisbelow(True)
ax.yaxis.grid(color='#FDAC53', linestyle='dashed', alpha=0.5)
# limit
plt.ylim(0,)
plt.tight_layout()
#plt.show()
plt.savefig('smooth_lines.png', facecolor='#293952')
@Thiagobc23
Copy link
Author

smooth_lines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment