#![allow(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::too_many_lines
)]
use crate::alpha::{marks::ObservationAlpha, AlphaTarget, AlphaUnitKind};
use crate::builder::PlotDescription;
use crate::layout::{Layout, PhysicalTextAlignment, PixelRect};
use crate::render::backend::{with_clip, Backend, GradientStop, LineStyle, Point2D};
use crate::spec::{PlotMeasureContext, PlotRenderResult};
use crate::Error;
#[derive(Debug)]
pub(crate) struct PreparedBeeswarm {
pub(crate) x_data: (f64, f64),
rows: Vec<(usize, f64, Option<f64>, ObservationAlpha)>,
mapped: Option<PreparedColor>,
}
#[derive(Debug)]
struct PreparedColor {
colors: Vec<crate::theme::OpaqueColor>,
selection: crate::theme::ContinuousColorScale,
scale: crate::theme::ContinuousColors,
colorbar_stops: Vec<GradientStop>,
values: Option<crate::numeric::set::FormattedSet>,
format: Option<std::sync::Arc<crate::numeric::format::NumericFormat>>,
color_label: crate::Text,
}
fn retained<'v>(
registered: Option<&'v crate::orchestrator::registration::PlotRegistration<'_>>,
) -> Result<(&'v PreparedBeeswarm, &'v [String]), Error> {
if registered.is_none() {
return Err(Error::Render(
"Beeswarm requires root-prepared source rows".into(),
));
}
match crate::layout::interior::preference::panel(registered, "Beeswarm")?.as_ref() {
crate::orchestrator::registration::FamilyRef::Beeswarm(marks) => Ok((
marks,
®istered
.expect("prepared Beeswarm occurrence")
.axes
.categories(1)
.expect("prepared Beeswarm categories")
.raw,
)),
_ => Err(Error::Render(
"Beeswarm requires root-prepared source rows".into(),
)),
}
}
pub(crate) fn intrinsic_body_minimum(
chart: &PlotDescription,
registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
intrinsic: &crate::orchestrator::root::PlotIntrinsics,
operation: &crate::font::canonical::OperationContext,
theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<(f64, f64), Error> {
let (prepared, levels) = retained(registered)?;
if levels.is_empty()
|| prepared.rows.is_empty()
|| prepared
.mapped
.as_ref()
.is_some_and(|mapped| mapped.colors.len() != prepared.rows.len())
{
return Err(Error::Render(
"Beeswarm source rows and prepared points differ".into(),
));
}
let point = point_style(chart, theme, (0, 0, 0));
let ink = crate::alpha::marks::point_ink(
&point,
prepared
.rows
.iter()
.map(|&(_, x, _, alpha)| (x, 0.0, alpha)),
)?;
let pitch = 2.0 * quanta_pixels(packing_radius(chart, theme)?);
for &(category, _, _, _) in &prepared.rows {
if category >= levels.len() {
return Err(Error::Render(
"Beeswarm point category exceeds prepared levels".into(),
));
}
}
let count = u32::try_from(levels.len())
.map_err(|_| Error::Render("Beeswarm category count exceeds spatial range".into()))?;
let height = pitch * f64::from(count);
if !height.is_finite() {
return Err(Error::Render(
"Beeswarm category hard span overflowed".into(),
));
}
let mut numeric = ink.map_or(0.0, |ink| ink.dimensions().0);
if chart.zero_line_visible() && prepared.x_data.0 <= 0.0 && prepared.x_data.1 >= 0.0 {
numeric = numeric.max(crate::render::geometry::line_ink_width(
&theme
.marks
.get_strokes()
.get_references()
.get_beeswarm_reference()
.backend_style(),
)?);
}
let axes = crate::orchestrator::root::coordinate_intrinsic(
intrinsic,
&crate::orchestrator::root::intrinsic_inputs(registered, theme, operation)?,
)?
.minimum(crate::orchestrator::registration::axis_tick_labels_visible(
registered, 1,
));
Ok((
axes.0.max(
if registered.expect("prepared occurrence").raw_windows()[0].is_none() {
numeric
} else {
0.0
},
),
axes.1.max(height),
))
}
fn quanta_pixels(value: i64) -> f64 {
value as f64 / 1024.0
}
fn point_style(
chart: &PlotDescription,
theme: &crate::theme::ResolvedTheme,
rgb: (u8, u8, u8),
) -> crate::render::backend::PointStyle {
let mut style = chart.point_style(
theme,
rgb,
theme.marks.get_points().get_radii().get_beeswarm(),
);
if let Some(color) = chart.beeswarm_fixed_color() {
style.color = color;
}
style
}
fn packing_radius(
chart: &PlotDescription,
theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<i64, Error> {
let mut style = point_style(chart, theme, (0, 0, 0));
style.color = style.color.with_alpha(1.0);
packing::radius(&style)
}
pub(crate) fn prepare(
chart: &crate::builder::PlotDescription,
data: crate::data::PlotData<'_, '_>,
appearance: &crate::theme::ResolvedTheme,
numeric: crate::numeric::source::NumericBinding<'_>,
materialization: crate::orchestrator::registration::ContinuousMaterialization,
) -> Result<(PreparedBeeswarm, Vec<String>), Error> {
let alpha = chart.prepare_alpha(AlphaTarget::Point, AlphaUnitKind::Observation, &[])?;
let category_col = chart
.y_col()
.ok_or_else(|| Error::Data("beeswarm: categorical row column not set".into()))?;
let x_col = chart
.x_col()
.ok_or_else(|| Error::Data("beeswarm: x column not set".into()))?;
let categories = crate::data::strict_strings(data, category_col, "beeswarm")?;
let xs = crate::data::strict_finite_f64(data, x_col, "beeswarm")?;
let colors = chart
.color_col()
.map(|column| crate::data::strict_finite_f64(data, column, "beeswarm"))
.transpose()?;
if categories.len() != xs.len()
|| xs.is_empty()
|| colors
.as_ref()
.is_some_and(|colors| colors.len() != xs.len())
{
return Err(Error::Data(
"beeswarm: category/x and any numeric color values must have equal non-zero lengths"
.into(),
));
}
let levels = crate::data::source::source_levels(&categories)?;
data.validate_row_source()?;
let x_data = crate::data::min_max(xs.iter().copied(), "beeswarm")?;
let mut indices = crate::data::source::collect_source(
levels.iter().enumerate().map(|(i, s)| Ok((s.as_str(), i))),
)?;
crate::data::source::sort_source_by(&mut indices, |a, b| a.0.cmp(b.0))?;
let mut rows =
crate::data::source::collect_source(categories.iter().zip(&xs).enumerate().map(
|(row, (category, x))| {
let index = indices
.binary_search_by_key(&category.as_str(), |entry| entry.0)
.map_err(|_| Error::Data("beeswarm: category identity missing".into()))?;
Ok((
indices[index].1,
*x,
colors.as_ref().map(|colors| colors[row]),
ObservationAlpha::resolve(data, &alpha, row)?,
))
},
))?;
crate::data::source::sort_source_by(&mut rows, |a, b| {
a.0.cmp(&b.0)
.then_with(|| a.3.source_row.cmp(&b.3.source_row))
})?;
let mapped = if let Some(colors) = colors {
let selection = chart.continuous_selection_in(appearance.color_scales())?;
let color_range = selection.prepared_domain(&colors, "beeswarm")?.as_pair();
let format = chart.color_label_format_spec().cloned();
numeric.check_data(data)?;
let values = if materialization
== crate::orchestrator::registration::ContinuousMaterialization::Local
{
Some(crate::decorations::legend::descriptor::domain_presentation(
color_range,
selection.get_center(),
format.as_deref().map(|format| {
(
format,
numeric,
if selection.get_domain().is_some() {
crate::formatting::NumericRangeOrigin::Explicit
} else {
crate::formatting::NumericRangeOrigin::Automatic
},
)
}),
)?)
} else {
None
};
let scale = crate::theme::ContinuousColors::selected(color_range, &selection)?;
let samples = crate::data::source::collect_source(
rows.iter()
.map(|row| Ok(row.2.expect("mapped color value"))),
)?;
let colorbar_stops = scale.guide_stops(&samples)?;
let colors =
crate::data::source::collect_source(samples.iter().map(|&value| scale.color(value)))?;
Some(PreparedColor {
colors,
values,
format,
scale,
selection,
colorbar_stops,
color_label: chart.prepare_color_label(None)?,
})
} else {
None
};
Ok((
PreparedBeeswarm {
x_data,
rows,
mapped,
},
levels,
))
}
impl PreparedBeeswarm {
pub(crate) fn alpha_guide(
&self,
chart: &crate::builder::PlotDescription,
theme: &crate::theme::ResolvedTheme,
guide: &mut crate::decorations::legend::alpha::AlphaGuideBuilder<'_>,
) -> crate::Result<()> {
let point = point_style(chart, theme, (0, 0, 0));
for &(_, _, _, alpha) in &self.rows {
guide.point(
crate::decorations::legend::alpha::AlphaGlyphRole::Primary,
alpha,
point.clone(),
false,
)?;
}
Ok(())
}
pub(crate) fn guide_samples(&self) -> Result<Vec<f64>, Error> {
crate::data::source::collect_source(self.rows.iter().filter_map(|row| row.2.map(Ok)))
}
pub(crate) fn install_shared_domain(
&mut self,
descriptor: &crate::decorations::legend::descriptor::ContinuousDescriptor,
) -> Result<(), Error> {
let mapped = self.mapped.as_mut().ok_or_else(|| {
Error::Render("unmapped Beeswarm cannot receive a continuous color domain".into())
})?;
let values = Some(descriptor.numeric.try_copy()?);
let scale =
crate::theme::ContinuousColors::selected(descriptor.domain, &descriptor.selection)?;
let colorbar_stops =
crate::data::source::collect_source(descriptor.stops.iter().copied().map(Ok))?;
mapped.values = values;
mapped.selection = descriptor.selection.clone();
mapped.scale = scale;
mapped.colorbar_stops = colorbar_stops;
for (color, row) in mapped.colors.iter_mut().zip(&self.rows) {
*color = mapped.scale.color(row.2.expect("mapped color value"))?;
}
Ok(())
}
pub(crate) fn continuous_semantics(
&self,
) -> Result<crate::decorations::legend::descriptor::ContinuousSemantics, Error> {
let mapped = self
.mapped
.as_ref()
.ok_or_else(|| Error::Render("Beeswarm has no continuous color source".into()))?;
Ok(
crate::decorations::legend::descriptor::ContinuousSemantics {
domain: mapped.scale.domain(),
selection: mapped.selection.clone(),
missing: None,
format: mapped.format.clone(),
},
)
}
pub(crate) fn color_label(&self) -> Result<&crate::Text, Error> {
self.mapped
.as_ref()
.map(|mapped| &mapped.color_label)
.ok_or_else(|| Error::Render("Beeswarm has no continuous color title".into()))
}
pub(crate) fn override_color_label(
&mut self,
chart: &PlotDescription,
labels: &crate::formatting::Labels,
) -> Result<(), Error> {
if let Some(mapped) = &mut self.mapped {
mapped.color_label = chart.prepare_color_label(Some(labels))?;
}
Ok(())
}
pub(crate) fn guide_descriptor(
&self,
field: crate::data::category::RawField,
) -> Result<Option<crate::decorations::legend::descriptor::ContinuousDescriptor>, Error> {
let Some(mapped) = &self.mapped else {
return Ok(None);
};
let Some(values) = &mapped.values else {
return Ok(None);
};
Ok(Some(
crate::decorations::legend::descriptor::ContinuousDescriptor {
field,
title: crate::data::source::source_arc(mapped.color_label.try_copy()?)?,
stops: crate::data::source::collect_source(
mapped.colorbar_stops.iter().copied().map(Ok),
)?,
selection: mapped.selection.clone(),
center: mapped.selection.get_center(),
missing: None,
domain: mapped.scale.domain(),
exact: mapped.selection.get_domain().is_some(),
format: mapped.format.clone(),
numeric: values.try_copy()?,
},
))
}
}
pub(crate) fn natural_body_height(
chart: &PlotDescription,
registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
intrinsic: &crate::orchestrator::root::PlotIntrinsics,
operation: &crate::font::canonical::OperationContext,
theme: &crate::text::TextRequestContext<'_, '_>,
width: f64,
selected_range: Option<(f64, f64)>,
) -> Result<f64, Error> {
if registered.is_none() {
return Err(Error::Render("natural Beeswarm rows missing".into()));
}
let crate::orchestrator::registration::FamilyRef::Beeswarm(marks) =
crate::layout::interior::preference::panel(registered, "natural Beeswarm")?.as_ref()
else {
return Err(Error::Render("natural Beeswarm rows missing".into()));
};
let axes = registered
.and_then(|registered| registered.axes.coordinate())
.ok_or_else(|| Error::Render("natural Beeswarm axes missing".into()))?;
let range = selected_range.unwrap_or_else(|| {
chart
.x_axis_spec()
.window
.map_or(axes.ranges()[0], crate::layout::RawWindow::pair)
});
let projection = crate::layout::Projection::new(range, (0.0, 1.0), (0.0, width, 0.0, 1.0));
let radius = packing_radius(chart, theme)?;
let packed = packing::pack(
marks
.rows
.iter()
.map(|&(category, value, _, alpha)| (category, value, alpha.source_row)),
&projection,
radius,
)?;
let hard = intrinsic_body_minimum(chart, registered, intrinsic, operation, theme)?;
let height = quanta_pixels(packed.hard_pitch)
.max(2.0 * theme.typography.axes.tick_label.font_size)
* axes
.categories(1)
.expect("prepared Beeswarm categories")
.raw
.len() as f64;
Ok(height.max(hard.1).max(3.0 * width / 4.0))
}
pub(crate) fn measure(
chart: &PlotDescription,
context: &PlotMeasureContext<'_, '_>,
request: &crate::text::TextRequestContext<'_, '_>,
) -> Result<PlotRenderResult, crate::layout::fit::PlanError> {
let (prepared, levels) = retained(Some(context.registered))?;
let theme = request;
let minimum = intrinsic_body_minimum(
chart,
Some(context.registered),
context.intrinsic(),
context.operation,
theme,
)?;
let descriptor =
if crate::orchestrator::registration::continuous_guide_suppressed(Some(context.registered))
|| crate::orchestrator::registration::continuous_guide_use(
chart,
Some(context.registered),
) != crate::decorations::legend::discrete::scoped::GuideUse::Local
|| context.guides.use_kind
!= crate::decorations::legend::discrete::scoped::GuideUse::Local
{
None
} else {
crate::orchestrator::registration::guide_descriptor(Some(context.registered))?
};
let (panel, colorbar) = if let Some(descriptor) = descriptor {
let guide_scope = context
.fit_scope()
.child(crate::layout::AddressRole::OutsideGuideRight, 0)?;
let (body, guide) = crate::layout::interior::guide::native_right(
descriptor,
context.assignment.local.body,
minimum.0,
theme,
&guide_scope,
context.assignment.local.content_height.then_some(context),
)?;
(body, Some(guide))
} else {
(context.assignment.local.body, None)
};
let axes = context
.registered
.axes
.coordinate()
.ok_or_else(|| Error::Render("Beeswarm axes require preparation".into()))?;
let range = context.axis_range(crate::layout::AxisSide::Bottom)?;
let projection =
crate::layout::Projection::new(range, (0.0, levels.len() as f64), panel.as_tuple());
let source = context.registered.source;
let pair = [axes.axis(source, 0), axes.axis(source, 1)];
let assigned = context
.axis_pair(crate::orchestrator::assignment::AxisPairScope::Pair)?
.axes;
let x = assigned[0].layout_ticks(
Vec::new(),
&projection,
crate::layout::AxisSide::Bottom,
theme,
context.fit_scope(),
context.registered.axis_numeric_binding(context.operation)?,
)?;
let radius = packing_radius(chart, theme)?;
let packed = packing::pack(
prepared
.rows
.iter()
.map(|&(category, value, _, alpha)| (category, value, alpha.source_row)),
&projection,
radius,
)?;
let labels = &axes
.categories(1)
.ok_or_else(|| Error::Render("Beeswarm category labels missing".into()))?;
let labels = &labels.ticks;
let mut hard_pitch = packed.hard_pitch;
let width = context.assignment.local.axis_label_width.max(1.0 / 1024.0);
let tick_appearance = theme.tick_text_appearance(crate::layout::AxisSide::Left);
if crate::orchestrator::registration::axis_tick_labels_visible(Some(context.registered), 1)
&& !tick_appearance.hidden()
&& !tick_appearance.layout.is_some_and(|request| {
request
.instructions()
.visibility
.as_ref()
.is_some_and(crate::text::TextVisibility::reduces)
})
{
let mut heights = crate::data::source::collect_source(labels.iter().map(|_| Ok(0.0)))?;
for index in pair[1]
.authored()
.expect("coordinate authored intent")
.category_labels
.indices(labels.len())
{
let plan = crate::layout::fit::measured(crate::layout::fit::text(
theme,
&labels[index].label,
tick_appearance,
width,
PhysicalTextAlignment::End,
"y-axis tick label",
&context
.fit_scope()
.child(crate::layout::AddressRole::AxisLeft, 0)?,
))?;
if !plan.lines.is_empty() {
heights[index] = plan.occupied_size().1 + 2.0 * crate::layout::LABEL_CLEARANCE;
}
}
let span = crate::layout::category_label_span(
&pair[1]
.authored()
.expect("coordinate authored intent")
.category_labels,
labels.len(),
|index| Ok(heights[index]),
)?;
hard_pitch = hard_pitch.max(crate::layout::kernel::ceil_spatial_quanta(
span / labels.len() as f64,
)?);
}
let preferred = hard_pitch.max(crate::layout::kernel::ceil_spatial_quanta(
2.0 * theme.typography.axes.tick_label.font_size,
)?);
let tracks = crate::data::source::collect_source(levels.iter().map(|_| {
Ok(crate::layout::kernel::TrackSpec {
min: hard_pitch,
preferred,
max: None,
flexible: true,
})
}))?;
let bands = crate::layout::interior::tracks::assign(
&tracks,
(panel.y0, panel.y1),
0.0,
false,
context.fit_scope(),
)?;
let ticks =
crate::data::source::collect_source(labels.iter().zip(&bands).map(|(label, band)| {
let middle = f64::midpoint(band.0, band.1);
Ok(crate::layout::AxisTick::new(
(middle - panel.y0) / panel.height() * levels.len() as f64,
crate::data::source::copy_source_string(&label.label)?,
))
}))?;
let layout = Layout {
projection,
x_axis: crate::layout::Axis {
label: axes.copy_label(context.registered, 0)?,
ticks: x.ticks,
tick_labels_visible: true,
category_labels: pair[0]
.authored()
.expect("coordinate authored intent")
.category_labels
.clone(),
source: x.source,
numeric: x.numeric,
explicit_ticks: pair[0].exact_ticks()?.is_some(),
assigned_tick_width: None,
assigned_cells: None,
},
y_axis: crate::layout::Axis {
label: axes.copy_label(context.registered, 1)?,
ticks,
tick_labels_visible: crate::orchestrator::registration::axis_tick_labels_visible(
Some(context.registered),
1,
),
category_labels: pair[1]
.authored()
.expect("coordinate authored intent")
.category_labels
.clone(),
source: crate::layout::TickSource::SUPPLIED,
numeric: None,
explicit_ticks: false,
assigned_tick_width: Some(width),
assigned_cells: Some(crate::data::source::collect_source(
bands.iter().map(|band| Ok(*band)),
)?),
},
};
let x_range = layout.projection.x_range();
let zero = if chart.zero_line_visible() && x_range.0 <= 0.0 && x_range.1 >= 0.0 {
let (x, y0) = layout.projection.project(0.0, 0.0);
let (_, y1) = layout.projection.project(0.0, levels.len() as f64);
Some((
[Point2D::new(x, y0), Point2D::new(x, y1)],
theme
.marks
.get_strokes()
.get_references()
.get_beeswarm_reference()
.backend_style(),
))
} else {
None
};
let default_rgb = if prepared.mapped.is_none() && chart.beeswarm_fixed_color().is_none() {
crate::theme::AccentColors::resolve(theme.marks.get_accents(), 1)?.color(0)?
} else {
(0, 0, 0)
};
let points = crate::data::source::collect_source(
packed
.points
.iter()
.zip(&prepared.rows)
.enumerate()
.map(|(index, (point, row))| {
let rgb = prepared
.mapped
.as_ref()
.map_or(default_rgb, |mapped| mapped.colors[index].as_rgb());
let band = bands[point.category];
let middle =
crate::layout::kernel::nearest_spatial_quanta(f64::midpoint(band.0, band.1))?;
let y = middle
.checked_add(point.offset)
.ok_or_else(|| Error::Render("Beeswarm arranged point overflow".into()))?;
Ok((
Point2D::new(quanta_pixels(point.x), quanta_pixels(y)),
row.3.point(point_style(chart, theme, rgb)),
))
}),
)?;
let mut payload = BeeswarmPayload {
clip: layout.projection.panel_box(),
zero,
points,
source_rows: crate::data::source::collect_source(
packed
.points
.iter()
.map(|point| Ok((point.category, point.source_row))),
)?,
domain_expansions: [None; 2],
colorbar: colorbar
.as_ref()
.map(|guide| select_colorbar(guide, panel))
.transpose()?,
};
let geometry = payload.geometry()?;
let mut full = crate::render::geometry::GeometrySnapshot::new();
for (point, style) in &payload.points {
full.scatter_with_clip(std::slice::from_ref(point), style, None)?;
}
let panel = layout.projection.panel_box();
if let Some(bounds) = full
.bounds()
.iter()
.copied()
.reduce(crate::render::geometry::GeometryBox::union)
{
if bounds.bottom < panel.y0 || bounds.top > panel.y1 {
return Err(context
.fit_scope()
.failure(
crate::layout::fit::FitKind::SpecializedGeometry,
"Beeswarm painted ink exceeds its assigned category panel",
)
.into());
}
}
if let Some((line, style)) = &payload.zero {
full.line(line, style, None)?;
}
if let Some(bounds) = full
.bounds()
.iter()
.copied()
.reduce(crate::render::geometry::GeometryBox::union)
{
if context.registered.raw_windows()[0].is_none() {
let levels = u32::try_from(levels.len()).map_err(|_| {
Error::Render("Beeswarm category count exceeds spatial range".into())
})?;
payload.domain_expansions = crate::layout::interior::automatic_absolute_ink_expansions(
[prepared.x_data, (0.0, f64::from(levels))],
&layout.projection,
bounds,
[true, false],
context.fit_scope(),
)?;
}
}
let mut result = PlotRenderResult::new(
layout,
crate::orchestrator::registration::guide_descriptor(Some(context.registered))?,
);
result.y_domain = crate::spec::AxisDomain::Categorical;
result.y_tick_keys =
Some(crate::data::source::collect_source(levels.iter().map(
|level| crate::data::source::copy_source_string(level),
))?);
result.axes = Some(result.layout.measure_axes_with_inputs(
theme,
context.fit_scope(),
context.semantic_inputs(crate::orchestrator::assignment::AxisPairScope::Pair)?,
|| crate::layout::CoordinateLayoutInputs::new(theme),
)?);
if let Some(bar) = &payload.colorbar {
for call in &bar.calls {
if let crate::decorations::legend::LegendCall::Text(text) = call {
crate::data::source::reserve_source(&mut result.producer_text, 1)?;
result.producer_text.push(text.clone());
}
}
}
result.marks = Some(crate::data::source::source_arc(
crate::layout::interior::SelectedMarkPlan {
payload: crate::layout::interior::MarkPayload::Beeswarm(payload),
geometry,
},
)?);
Ok(result)
}
#[derive(Debug)]
pub(crate) struct BeeswarmPayload {
clip: PixelRect,
zero: Option<([Point2D; 2], LineStyle)>,
points: Vec<(Point2D, crate::render::backend::PointStyle)>,
source_rows: Vec<(usize, usize)>,
colorbar: Option<crate::decorations::legend::LegendDrawPlan>,
pub(crate) domain_expansions: [Option<crate::layout::interior::DomainExpansion>; 2],
}
impl BeeswarmPayload {
pub(crate) fn observe_sources(
&self,
round: &mut crate::layout::kernel::FeedbackRound,
) -> Result<(), Error> {
round.observe_count(self.source_rows.len())?;
for &(category, row) in &self.source_rows {
round.observe_count(category)?;
round.observe_count(row)?;
}
Ok(())
}
pub(crate) fn draw(&self, backend: &mut dyn Backend) -> Result<(), Error> {
with_clip(backend, self.clip, |backend| {
if let Some((line, style)) = &self.zero {
backend.draw_line(line, style)?;
}
for (point, style) in &self.points {
backend.draw_scatter(&[*point], style)?;
}
Ok(())
})?;
if let Some(bar) = &self.colorbar {
bar.draw(backend)?;
}
Ok(())
}
fn geometry(&self) -> Result<crate::render::geometry::GeometrySnapshot, Error> {
let mut geometry = crate::render::geometry::GeometrySnapshot::new();
let clip = crate::render::backend::validate_clip_region(self.clip)?.panel();
if let Some((line, style)) = &self.zero {
geometry.line(line, style, Some(clip))?;
}
for (point, style) in &self.points {
geometry.scatter(&[*point], style, clip)?;
}
if let Some(bar) = &self.colorbar {
bar.geometry(&mut geometry)?;
}
Ok(geometry)
}
}
fn select_colorbar(
guide: &crate::decorations::legend::Legend,
panel: PixelRect,
) -> Result<crate::decorations::legend::LegendDrawPlan, Error> {
let bounds = guide.box_at(
panel.x1 + guide.metrics.outside_gap,
panel.y0 + (panel.height() - guide.allocation_height()) / 2.0,
);
guide.select(bounds?)
}
mod packing;