Certainly! Let's rewrite your code using the seaborn objects interface. The seaborn objects interface provides a more flexible and powerful way to create plots, especially when you need to use custom functions or perform complex data manipulations. Here's how you can modify your code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn.objects as so
from utils.mymath import online_mean_and_ci
bins = np.linspace(0, 1, 23)
def x_y_from_file(file_path):
# example processing:
data = np.load(file_path)
y, x = np.histogram(data, bins)
return x, y
def load_and_average(data, *, ax, **kws):
bin_edges = np.linspace(0, 1, 23)
bin_centers = (bin_edges[1:] + bin_edges[:-1]) / 2
mean_density, ci_low, ci_high = online_mean_and_ci(
data_iterator=(x_y_from_file(p)[1] for p in data['path']), alpha=0.1
)
color = kws.get('color', None)
if color is None:
# Use the default color cycle if color is not specified
color = next(ax._get_lines.prop_cycler)['color']
ax.plot(bin_centers, mean_density, color=color)
ax.fill_between(bin_centers, ci_low, ci_high, color=color, alpha=0.2)
# Create the plot using seaborn objects interface
p = so.Plot(agents_crosslink_df, color='param1')
p = p.facet('param2', 'param3', margin_titles=True)
p = p.add(so.Function(load_and_average))
p = p.legend()
p = p.show()
Explanation:
-
Import seaborn objects module:
We import seaborn.objects as so to access the new objects interface.
-
Define your data processing functions:
x_y_from_file(file_path) remains the same.
load_and_average(data, *, ax, **kws) is modified to match the expected signature for custom functions in the objects interface.
-
Modify load_and_average function:
- It now accepts
data and ax (the current axes) as parameters.
- We retrieve
color from **kws (keyword arguments), which will contain mappings from the plot, including aesthetics like color.
- We ensure a default color is used if
color is not provided.
- The plotting commands remain the same, using
ax.plot and ax.fill_between.
-
Create the plot:
- We instantiate a
Plot object with agents_crosslink_df and map color to 'param1'.
- We use
.facet('param2', 'param3', margin_titles=True) to create a grid of plots based on these parameters.
- We add our custom function
load_and_average using .add(so.Function(load_and_average)).
- We add a legend with
.legend().
- Finally, we display the plot with
.show().
This approach leverages the seaborn objects interface to handle faceting and aesthetic mappings while using your custom function to process and plot the data. The key is ensuring your custom function accepts the correct parameters (data, ax, and **kws) and that you map your variables appropriately in the Plot object.