Struct Plot

Source
pub struct Plot<T: Data> { /* private fields */ }
Expand description

The type of a plot widget.

See Plot::new for information on how to construct this.

This implements druid::Widget so it can be used like any other widget type.

fn build_plot_widget() -> impl Widget<()> {
    // ... construct and return widget using Plot::new()
}

let main_window = WindowDesc::new(build_plot_widget());

Implementations§

Source§

impl<T: Data> Plot<T>

Source

pub fn new( f: impl Fn((u32, u32), &T, &DrawingArea<PietBackend<'_, '_>, Shift>) + 'static, ) -> Plot<T>

Create a plot widget

This takes a function that should draw the plot using the normal plotters API. The function has access to the width and height of the plotting area, to the Data of the rust widget, and to a plotters DrawingArea.

Plot::new(|(width, height), data: &AppState, root| {
    root.fill(&WHITE).unwrap();
    let mut chart = ChartBuilder::on(&root)
        .build_cartesian_2d(-1f32..1f32, -0.1f32..1f32)
        .unwrap();

    // see the plotters documentation on how to use `chart`
});
Examples found in repository?
examples/simple.rs (lines 6-35)
5fn build_plot_widget() -> impl Widget<()> {
6    Plot::new(|_size, _data, root| {
7        // Code taken from the plotters example: https://github.com/38/plotters#quick-start
8        root.fill(&WHITE).unwrap();
9        let mut chart = ChartBuilder::on(&root)
10            .caption("y=x^2", ("sans-serif", 50).into_font())
11            .margin(5)
12            .margin_right(15)
13            .x_label_area_size(30)
14            .y_label_area_size(30)
15            .build_cartesian_2d(-1f32..1f32, -0.1f32..1f32)
16            .unwrap();
17
18        chart.configure_mesh().draw().unwrap();
19
20        chart
21            .draw_series(LineSeries::new(
22                (-50..=50).map(|x| x as f32 / 50.0).map(|x| (x, x * x)),
23                &RED,
24            ))
25            .unwrap()
26            .label("y = x^2")
27            .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], &RED));
28
29        chart
30            .configure_series_labels()
31            .background_style(&WHITE.mix(0.8))
32            .border_style(&BLACK)
33            .draw()
34            .unwrap();
35    })
36}
More examples
Hide additional examples
examples/interactive.rs (lines 14-63)
13fn build_plot_widget() -> impl Widget<State> {
14    Plot::new(|_size, data: &State, root| {
15        let μ = data.μ as f32;
16
17        let res = 400;
18        let font = FontDesc::new(FontFamily::SansSerif, 16., FontStyle::Normal);
19
20        let mut chart = ChartBuilder::on(&root)
21            .x_label_area_size(30)
22            .y_label_area_size(30)
23            .margin_right(10)
24            .build_cartesian_2d(0.0..1_f32, 0.0..6_f32)
25            .unwrap();
26
27        chart
28            .configure_mesh()
29            .axis_style(&RGBColor(28, 28, 28))
30            .x_label_style(font.clone().with_color(&WHITE))
31            .y_label_style(font.clone().with_color(&WHITE))
32            .draw()
33            .unwrap();
34
35        for (σ, idx) in [0.32_f32, 0.56, 1., 1.78, 3.16].into_iter().zip(0..) {
36            let fac = 1. / (σ * std::f32::consts::TAU.sqrt());
37            let color = Palette99::pick(idx);
38
39            let data = (0..res).map(|x| x as f32 / res as f32).map(|x| {
40                let y = fac * (-(logit(x) - μ).powi(2) / (2. * σ.powi(2))).exp() / (x * (1. - x));
41                (x, y)
42            });
43
44            chart
45                .draw_series(LineSeries::new(data, &color))
46                .unwrap()
47                .label(format!("σ = {σ}"))
48                .legend(move |(x, y)| {
49                    PathElement::new(
50                        vec![(x, y), (x + 20, y)],
51                        ShapeStyle::from(&color).stroke_width(2),
52                    )
53                });
54        }
55        chart
56            .configure_series_labels()
57            .position(SeriesLabelPosition::UpperRight)
58            .background_style(&RGBColor(41, 41, 41))
59            .border_style(&RGBColor(28, 28, 28))
60            .label_font(font.with_color(&WHITE))
61            .draw()
62            .unwrap();
63    })
64}

Trait Implementations§

Source§

impl<T> Widget<T> for Plot<T>
where T: Data,

Source§

fn event(&mut self, _: &mut EventCtx<'_, '_>, _: &Event, _: &mut T, _: &Env)

Handle an event. Read more
Source§

fn lifecycle( &mut self, _: &mut LifeCycleCtx<'_, '_>, _: &LifeCycle, _: &T, _: &Env, )

Handle a life cycle notification. Read more
Source§

fn update( &mut self, ctx: &mut UpdateCtx<'_, '_>, old_data: &T, data: &T, _env: &Env, )

Update the widget’s appearance in response to a change in the app’s Data or Env. Read more
Source§

fn layout( &mut self, _: &mut LayoutCtx<'_, '_>, bc: &BoxConstraints, _: &T, _: &Env, ) -> Size

Compute layout. Read more
Source§

fn paint(&mut self, ctx: &mut PaintCtx<'_, '_, '_>, data: &T, _: &Env)

Paint the widget appearance. Read more
Source§

fn compute_max_intrinsic( &mut self, axis: Axis, ctx: &mut LayoutCtx<'_, '_>, bc: &BoxConstraints, data: &T, env: &Env, ) -> f64

Computes max intrinsic/preferred dimension of a widget on the provided axis. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Plot<T>

§

impl<T> !RefUnwindSafe for Plot<T>

§

impl<T> !Send for Plot<T>

§

impl<T> !Sync for Plot<T>

§

impl<T> Unpin for Plot<T>

§

impl<T> !UnwindSafe for Plot<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> RoundFrom<T> for T

Source§

fn round_from(x: T) -> T

Performs the conversion.
Source§

impl<T, U> RoundInto<U> for T
where U: RoundFrom<T>,

Source§

fn round_into(self) -> U

Performs the conversion.
Source§

impl<T, W> TestWidgetExt<T> for W
where T: Data, W: Widget<T> + 'static,

Source§

fn record(self, recording: &Recording) -> Recorder<Self>

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, W> WidgetExt<T> for W
where T: Data, W: Widget<T> + 'static,

Source§

fn padding(self, insets: impl Into<KeyOrValue<Insets>>) -> Padding<T, Self>

Wrap this widget in a Padding widget with the given Insets. Read more
Source§

fn center(self) -> Align<T>

Wrap this widget in an Align widget, configured to center it.
Source§

fn align_left(self) -> Align<T>

Wrap this widget in an Align widget, configured to align left.
Source§

fn align_right(self) -> Align<T>

Wrap this widget in an Align widget, configured to align right.
Source§

fn align_vertical(self, align: UnitPoint) -> Align<T>

Wrap this widget in an Align widget, configured to align vertically.
Source§

fn align_horizontal(self, align: UnitPoint) -> Align<T>

Wrap this widget in an Align widget, configured to align horizontally.
Source§

fn fix_width(self, width: impl Into<KeyOrValue<f64>>) -> SizedBox<T>

Wrap this widget in a SizedBox with an explicit width.
Source§

fn fix_height(self, height: impl Into<KeyOrValue<f64>>) -> SizedBox<T>

Wrap this widget in a SizedBox with an explicit height.
Source§

fn fix_size( self, width: impl Into<KeyOrValue<f64>>, height: impl Into<KeyOrValue<f64>>, ) -> SizedBox<T>

Wrap this widget in an SizedBox with an explicit width and height
Source§

fn expand(self) -> SizedBox<T>

Wrap this widget in a SizedBox with an infinite width and height. Read more
Source§

fn expand_width(self) -> SizedBox<T>

Wrap this widget in a SizedBox with an infinite width. Read more
Source§

fn expand_height(self) -> SizedBox<T>

Wrap this widget in a SizedBox with an infinite width. Read more
Source§

fn background(self, brush: impl Into<BackgroundBrush<T>>) -> Container<T>

Wrap this widget in a Container with the provided background brush. Read more
Source§

fn foreground(self, brush: impl Into<BackgroundBrush<T>>) -> Container<T>

Wrap this widget in a Container with the provided foreground brush. Read more
Source§

fn border( self, color: impl Into<KeyOrValue<Color>>, width: impl Into<KeyOrValue<f64>>, ) -> Container<T>

Wrap this widget in a Container with the given border. Read more
Source§

fn env_scope(self, f: impl Fn(&mut Env, &T) + 'static) -> EnvScope<T, Self>

Wrap this widget in a EnvScope widget, modifying the parent Env with the provided closure.
Source§

fn controller<C>(self, controller: C) -> ControllerHost<Self, C>
where C: Controller<T, Self>,

Wrap this widget with the provided Controller.
Source§

fn on_added( self, f: impl Fn(&mut Self, &mut LifeCycleCtx<'_, '_>, &T, &Env) + 'static, ) -> ControllerHost<Self, Added<T, Self>>

Provide a closure that will be called when this widget is added to the widget tree. Read more
Source§

fn on_click( self, f: impl Fn(&mut EventCtx<'_, '_>, &mut T, &Env) + 'static, ) -> ControllerHost<Self, Click<T>>

Control the events of this widget with a Click widget. The closure provided will be called when the widget is clicked with the left mouse button. Read more
Source§

fn debug_paint_layout(self) -> EnvScope<T, Self>

Draw the layout Rects of this widget and its children.
Source§

fn debug_widget_id(self) -> EnvScope<T, Self>

Display the WidgetIds for this widget and its children, when hot. Read more
Source§

fn debug_invalidation(self) -> DebugInvalidation<T, Self>

Draw a color-changing rectangle over this widget, allowing you to see the invalidation regions.
Source§

fn debug_widget(self) -> EnvScope<T, Self>

Set the DEBUG_WIDGET env variable for this widget (and its descendants). Read more
Source§

fn lens<S, L>(self, lens: L) -> LensWrap<S, T, L, Self>
where S: Data, L: Lens<S, T>,

Wrap this widget in a LensWrap widget for the provided Lens.
Source§

fn with_id(self, id: WidgetId) -> IdentityWrapper<Self>

Assign the widget a specific WidgetId. Read more
Source§

fn boxed(self) -> Box<dyn Widget<T>>

Wrap this widget in a Box.
Source§

fn scroll(self) -> Scroll<T, Self>

Wrap this widget in a Scroll widget.
Source§

fn disabled_if( self, disabled_if: impl Fn(&T, &Env) -> bool + 'static, ) -> DisabledIf<T, Self>

Wrap this widget in a DisabledIf widget. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more