| 1 | package Chart::GGPlot::Backend::Plotly::Geom::Raster; | ||
| 2 | |||
| 3 | # ABSTRACT: Chart::GGPlot's Plotly implementation for Geom::Raster | ||
| 4 | |||
| 5 | use Chart::GGPlot::Class qw(:pdl); | ||
| 6 | |||
| 7 | our $VERSION = '0.002003'; # VERSION | ||
| 8 | |||
| 9 | with qw(Chart::GGPlot::Backend::Plotly::Geom); | ||
| 10 | |||
| 11 | use List::AllUtils qw(pairwise); | ||
| 12 | use Module::Load; | ||
| 13 | use PDL::Primitive qw(which); | ||
| 14 | |||
| 15 | use Chart::GGPlot::Backend::Plotly::Util qw(to_rgb); | ||
| 16 | use Chart::GGPlot::Util qw(rescale); | ||
| 17 | |||
| 18 | classmethod to_traces ($df, $params, $plot) { | ||
| 19 | |||
| 20 | # TODO: see when we shall use Heatmapgl. | ||
| 21 | # It looks like that Heatmapgl's has a performance problem, see | ||
| 22 | # https://github.com/plotly/plotly.js/issues/1827 | ||
| 23 | my $plotly_trace_class = 'Chart::Plotly::Trace::Heatmap'; | ||
| 24 | load $plotly_trace_class; | ||
| 25 | |||
| 26 | my ( $x, $y ) = map { $df->at($_)->uniq->qsort } qw(x y); | ||
| 27 | |||
| 28 | my $to_2d_arrayref = sub { | ||
| 29 | my ($p) = @_; | ||
| 30 | return $p->copy->reshape( $x->length, $y->length )->unpdl; | ||
| 31 | }; | ||
| 32 | |||
| 33 | my $z = &$to_2d_arrayref( $df->at('fill_raw') ); | ||
| 34 | my $text = &$to_2d_arrayref( $df->at('hovertext') ); | ||
| 35 | |||
| 36 | my $color_scale = $df->select_columns( ['fill'] ); | ||
| 37 | |||
| 38 | # color scale must not have BAD values | ||
| 39 | my $rindices = which( $color_scale->at('fill')->isgood ); | ||
| 40 | $color_scale = $color_scale->select_rows($rindices); | ||
| 41 | $color_scale->set( 'fill_raw', $df->at('fill_raw')->slice($rindices) ); | ||
| 42 | $color_scale->set( 'alpha', $df->at('alpha')->slice($rindices) ); | ||
| 43 | |||
| 44 | $color_scale = $color_scale->sort( ['fill_raw'] )->uniq; | ||
| 45 | |||
| 46 | # colorscale must cover [0, 1] | ||
| 47 | my @values = do { | ||
| 48 | my $fill_raw = $color_scale->at('fill_raw'); | ||
| 49 | rescale( $fill_raw, pdl( [ 0, 1 ] ), pdl( $fill_raw->minmax ) )->list; | ||
| 50 | }; | ||
| 51 | my @colors = | ||
| 52 | to_rgb( $color_scale->at('fill'), $color_scale->at('alpha') )->list; | ||
| 53 | |||
| 54 | $color_scale = [ pairwise { [ $a, $b ] } @values, @colors ]; | ||
| 55 | |||
| 56 | my $trace = $plotly_trace_class->new( | ||
| 57 | x => $x->unpdl, | ||
| 58 | y => $y->unpdl, | ||
| 59 | z => $z, | ||
| 60 | hoverinfo => 'text', | ||
| 61 | text => $text, | ||
| 62 | colorscale => $color_scale, | ||
| 63 | showscale => 0, | ||
| 64 | autocolorscale => 0, | ||
| 65 | ); | ||
| 66 | return [ $class->_adjust_trace_for_flip( $trace, $plot ) ]; | ||
| 67 | } | ||
| 68 | |||
| 69 | __PACKAGE__->meta->make_immutable; | ||
| 70 | |||
| 71 | 1; | ||
| 72 | |||
| 73 | __END__ |