Skip to content

Instantly share code, notes, and snippets.

@mluerig
Last active July 26, 2024 00:26
Show Gist options
  • Save mluerig/b4ea5c3744c3747c76f9400e2ea8b3f1 to your computer and use it in GitHub Desktop.
Save mluerig/b4ea5c3744c3747c76f9400e2ea8b3f1 to your computer and use it in GitHub Desktop.
Pictogram-based figure in Python - see https://www.luerig.net/posts/interactive-figures/
## load modules
import os
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
## set wd
os.chdir(r"D:\workspace\figures\interactive_figures")
## load data (see gist interactive_figure_data_collection.py for how it was collected)
df_data = pd.read_csv(r"data\isopods_traits.csv")
## add regression line (optional)
fit = np.polyfit(df_data["log_length"], df_data["pigmentation"], 1, full=True)
slope, intercept = fit[0][0], fit[0][1]
line_x = np.linspace(df_data["log_length"].min(), df_data["log_length"].max(), 100)
line_y = slope * line_x + intercept
## create scatter plot
fig, ax = plt.subplots(figsize=(5, 5))
plt.tight_layout(pad=3)
ax.set_xlabel("Length (mm, log)")
ax.set_ylabel("Pigmentation (0-1)")
scatter = ax.scatter(df_data['log_length'], df_data['pigmentation'], s=5)
ax.plot(line_x, line_y, color='red', linewidth=2)
## add pictograms
for idx, row in df_data.iterrows():
if os.path.isfile(row["filepath"]):
image = cv2.imread(row["filepath"], cv2.IMREAD_UNCHANGED)
image = cv2.cvtColor(image, cv2.COLOR_BGRA2RGBA)
ab = AnnotationBbox(OffsetImage(image, zoom=0.2),
(row["log_length"], row["pigmentation"]), frameon=False)
ax.add_artist(ab)
## show / save
fig.show()
figure_path = r"figures\figure_isopods_pictograms.jpg"
fig.savefig(figure_path, dpi=500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment