Skip to content

Instantly share code, notes, and snippets.

@Thiagobc23
Last active November 2, 2021 02:25
Show Gist options
  • Save Thiagobc23/9a2f50cdd787eb27e99a2776cd1cf97d to your computer and use it in GitHub Desktop.
Save Thiagobc23/9a2f50cdd787eb27e99a2776cd1cf97d to your computer and use it in GitHub Desktop.
Connected Scatter Plot with Matplotlib
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
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
# data
x = df['Price']
y = df['Exchange Rate']
# points n segments
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
# figure
fig, ax = plt.subplots(1, figsize=(12,7), facecolor='#293952')
ax.set_facecolor('#293952')
# create a collection of lines
lc = LineCollection(segments, cmap='Wistia' , alpha=0.9)
# set the data that'll define the colors
lc.set_array(df.index) # try changing df.index for x or y
lc.set_linewidth(2.5)
# plot line collection
ax.add_collection(lc)
# date labels left
labels_df_l = df[df['Date'].isin(['2019-01', '2020-04', '2020-07'])].copy()
for key, record in labels_df_l.iterrows():
ax.text(record['Price'] + 0.2, record['Exchange Rate'], record['Date'], color='w')
# date labels right
labels_df_r = df[df['Date'].isin(['2019-03', '2019-06', '2019-12', '2021-01', '2021-06'])].copy()
for key, record in labels_df_r.iterrows():
ax.text(record['Price'] - 0.25, record['Exchange Rate'], record['Date'], color='w', ha='right')
# labels n title
ax.set_xlabel('Price', color='w')
ax.set_ylabel('Exchange Rate', color='w')
ax.set_title('Price and Exchange Rate - Product XYZ\n', loc='left', color='w', fontsize=18)
# 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')
# tick colors
ax.tick_params(axis='both', colors='w')
# grids
ax.set_axisbelow(True)
ax.yaxis.grid(color='#FDAC53', linestyle='dashed', alpha=0.3)
ax.xaxis.grid(color='#FDAC53', linestyle='dashed', alpha=0.3)
# limits
ax.set_xlim(0, x.max() + 3)
ax.set_ylim(0, y.max() + 3)
plt.tight_layout()
#plt.show()
plt.savefig('connected_scatter.png', facecolor='#293952')
@Thiagobc23
Copy link
Author

connected_scatter

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