Class: Charty::Backends::Plotly

Inherits:
Object
  • Object
show all
Defined in:
lib/charty/backends/plotly.rb

Defined Under Namespace

Modules: IRubyOutput Classes: HTML

Constant Summary collapse

PLOTLY_HISTNORM =
{
  count: "".freeze,
  frequency: "density".freeze,
  density: "probability density".freeze,
  probability: "probability".freeze
}.freeze

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.chart_idObject



19
20
21
# File 'lib/charty/backends/plotly.rb', line 19

def chart_id
  @chart_id ||= 0
end

.plotly_srcObject



29
30
31
# File 'lib/charty/backends/plotly.rb', line 29

def plotly_src
  @plotly_src ||= 'https://cdn.plot.ly/plotly-latest.min.js'
end

.with_api_load_tagObject



23
24
25
26
27
# File 'lib/charty/backends/plotly.rb', line 23

def with_api_load_tag
  return @with_api_load_tag unless @with_api_load_tag.nil?

  @with_api_load_tag = true
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



14
15
16
# File 'lib/charty/backends/plotly.rb', line 14

def context
  @context
end

Class Method Details

.ensure_playwrightObject



923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
# File 'lib/charty/backends/plotly.rb', line 923

def self.ensure_playwright
  if @playwright_fiber.nil?
    begin
      require "playwright"
    rescue LoadError
      $stderr.puts "ERROR: You need to install playwright and playwright-ruby-client before using Plotly renderer"
      raise
    end

    @playwright_fiber = Fiber.new do
      playwright_cli_executable_path = ENV.fetch("PLAYWRIGHT_CLI_EXECUTABLE_PATH", "npx playwright")
      Playwright.create(playwright_cli_executable_path: playwright_cli_executable_path) do |playwright|
        playwright.chromium.launch(headless: true) do |browser|
          request = Fiber.yield
          loop do
            result = nil
            case request.shift
            when :finish
              break
            when :render
              input, output, format, element_id, width, height = request

              page = browser.new_page
              page.set_viewport_size(width: width, height: height)
              page.goto("file://#{input}")
              element = page.query_selector("\##{element_id}")

              kwargs = {type: format}
              kwargs[:path] = output unless output.nil?
              result = element.screenshot(**kwargs)
            end
            request = Fiber.yield(result)
          end
        end
      end
    end
    @playwright_fiber.resume
  end
end

.notebook_rendererObject

for new APIs



850
851
852
# File 'lib/charty/backends/plotly.rb', line 850

def self.notebook_renderer
  @notebook_renderer ||= PlotlyHelpers::NotebookRenderer.new
end

.render_image(input, output, format, element_id, width, height) ⇒ Object



971
972
973
974
# File 'lib/charty/backends/plotly.rb', line 971

def self.render_image(input, output, format, element_id, width, height)
  ensure_playwright if @playwright_fiber.nil?
  @playwright_fiber.resume([:render, input, output, format.to_s, element_id, width, height])
end

.terminate_playwrightObject



963
964
965
966
967
# File 'lib/charty/backends/plotly.rb', line 963

def self.terminate_playwright
  return if @playwright_fiber.nil?

  @playwright_fiber.resume([:finish])
end

Instance Method Details

#add_line_plot_legend(variables, color_mapper, size_mapper, style_mapper, legend) ⇒ Object



501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'lib/charty/backends/plotly.rb', line 501

def add_line_plot_legend(variables, color_mapper, size_mapper, style_mapper, legend)
  if legend == :full
    warn("Plotly backend does not support full verbosity legend")
  end

  legend_order = if variables.key?(:color)
                   if variables.key?(:style)
                     # both color and style
                     color_mapper.levels.product(style_mapper.levels)
                   else
                     # only color
                     color_mapper.levels
                   end
                 elsif variables.key?(:style)
                   # only style
                   style_mapper.levels
                 else
                   # no legend entries
                   nil
                 end

  if legend_order
    # sort traces
    legend_index = legend_order.map.with_index { |name, i|
      [Array(name).uniq.join(", "), i]
    }.to_h
    @traces = @traces.each_with_index.sort_by { |trace, trace_index|
      index = legend_index.fetch(trace[:name], legend_order.length)
      [index, trace_index]
    }.map(&:first)

    # remove duplicated legend entries
    names = {}
    @traces.each do |trace|
      if trace[:showlegend] != false
        name = trace[:name]
        if name
          if names.key?(name)
            # Hide duplications
            trace[:showlegend] = false
          else
            trace[:showlegend] = true
            names[name] = true
          end
        else
          # Hide no name trace in legend
          trace[:showlegend] = false
        end
      end
    end
  end
end

#add_scatter_plot_legend(variables, color_mapper, size_mapper, style_mapper, legend) ⇒ Object



365
366
367
368
369
# File 'lib/charty/backends/plotly.rb', line 365

def add_scatter_plot_legend(variables, color_mapper, size_mapper, style_mapper, legend)
  if legend == :full
    warn("Plotly backend does not support full verbosity legend")
  end
end

#bar(bar_pos, group_names, values, colors, orient, label: nil, width:, align: :center, conf_int: nil, error_colors: nil, error_width: nil, cap_size: nil) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/charty/backends/plotly.rb', line 129

def bar(bar_pos, group_names, values, colors, orient, label: nil, width: 0.8r,
        align: :center, conf_int: nil, error_colors: nil, error_width: nil, cap_size: nil)
  bar_pos = Array(bar_pos)
  values = Array(values)
  colors = Array(colors).map(&:to_hex_string)

  if orient == :v
    x, y = bar_pos, values
  else
    x, y = values, bar_pos
  end

  trace = {
    type: :bar,
    orientation: orient,
    x: x,
    y: y,
    width: width,
    marker: {color: colors}
  }
  trace[:name] = label unless label.nil?

  unless conf_int.nil?
    errors_low = conf_int.map.with_index {|(low, _), i| values[i] - low }
    errors_high = conf_int.map.with_index {|(_, high), i| high - values[i] }

    error_bar = {
      type: :data,
      visible: true,
      symmetric: false,
      array: errors_high,
      arrayminus: errors_low,
      color: error_colors[0].to_hex_string
    }
    error_bar[:thickness] = error_width unless error_width.nil?
    error_bar[:width] = cap_size unless cap_size.nil?

    error_bar_key = orient == :v ? :error_y : :error_x
    trace[error_bar_key] = error_bar
  end

  @traces << trace

  if group_names
    @layout[:barmode] = :group
  end
end

#begin_figureObject



124
125
126
127
# File 'lib/charty/backends/plotly.rb', line 124

def begin_figure
  @traces = []
  @layout = {showlegend: false}
end

#box_plot(plot_data, group_names, orient:, colors:, gray:, dodge:, width:, flier_size: 5, whisker: 1.5, notch: false) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/charty/backends/plotly.rb', line 177

def box_plot(plot_data, group_names,
             orient:, colors:, gray:, dodge:, width: 0.8r,
             flier_size: 5, whisker: 1.5, notch: false)
  colors = Array(colors).map(&:to_hex_string)
  gray = gray.to_hex_string
  width = Float(width)
  flier_size = Float(width)
  whisker = Float(whisker)

  traces = plot_data.map.with_index do |group_data, i|
    group_data = Array(group_data)
    trace = {
      type: :box,
      orientation: orient,
      name: group_names[i],
      marker: {color: colors[i]}
    }
    if orient == :v
      trace.update(y: group_data)
    else
      trace.update(x: group_data)
    end

    trace
  end

  traces.reverse! if orient == :h

  @traces.concat(traces)
end

#disable_xaxis_gridObject



686
687
688
# File 'lib/charty/backends/plotly.rb', line 686

def disable_xaxis_grid
  # do nothing
end

#disable_yaxis_gridObject



690
691
692
# File 'lib/charty/backends/plotly.rb', line 690

def disable_yaxis_grid
  # do nothing
end

#grouped_box_plot(plot_data, group_names, color_names, orient:, colors:, gray:, dodge:, width:, flier_size: 5, whisker: 1.5, notch: false) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/charty/backends/plotly.rb', line 208

def grouped_box_plot(plot_data, group_names, color_names,
                     orient:, colors:, gray:, dodge:, width: 0.8r,
                     flier_size: 5, whisker: 1.5, notch: false)
  colors = Array(colors).map(&:to_hex_string)
  gray = gray.to_hex_string
  width = Float(width)
  flier_size = Float(width)
  whisker = Float(whisker)

  @layout[:boxmode] = :group

  if orient == :h
    @layout[:xaxis] ||= {}
    @layout[:xaxis][:zeroline] = false

    plot_data = plot_data.map {|d| d.reverse }
    group_names = group_names.reverse
  end

  traces = color_names.map.with_index do |color_name, i|
    group_keys = group_names.flat_map.with_index { |name, j|
      Array.new(plot_data[i][j].length, name)
    }.flatten

    values = plot_data[i].flat_map {|d| Array(d) }

    trace = {
      type: :box,
      orientation: orient,
      name: color_name,
      marker: {color: colors[i]}
    }

    if orient == :v
      trace.update(y: values, x: group_keys.map(&:to_s))
    else
      trace.update(x: values, y: group_keys.map(&:to_s))
    end

    trace
  end

  @traces.concat(traces)
end

#initilizeObject



34
35
# File 'lib/charty/backends/plotly.rb', line 34

def initilize
end

#invert_yaxisObject



694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
# File 'lib/charty/backends/plotly.rb', line 694

def invert_yaxis
  @traces.each do |trace|
    case trace[:type]
    when :bar
      trace[:y].reverse!
    end
  end

  if @layout[:boxmode] == :group
    @traces.reverse!
  end

  if @layout[:yaxis] && @layout[:yaxis][:ticktext]
    @layout[:yaxis][:ticktext].reverse!
  end
end

#label(x, y) ⇒ Object



37
38
# File 'lib/charty/backends/plotly.rb', line 37

def label(x, y)
end

#legend(loc:, title:) ⇒ Object



711
712
713
714
715
716
717
718
719
# File 'lib/charty/backends/plotly.rb', line 711

def legend(loc:, title:)
  @layout[:showlegend] = true
  @layout[:legend] = {
    title: {
      text: title
    }
  }
  # TODO: Handle loc
end

#line(x, y, variables, color:, color_mapper:, size:, size_mapper:, style:, style_mapper:, ci_params:) ⇒ Object



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/charty/backends/plotly.rb', line 378

def line(x, y, variables, color:, color_mapper:, size:, size_mapper:, style:, style_mapper:, ci_params:)
  x = case x
      when Charty::Vector
        x.to_a
      else
        orig_x, x = x, Array.try_convert(x)
        if x.nil?
          raise ArgumentError, "Invalid value for x: %p" % orig_x
        end
      end

  y = case y
      when Charty::Vector
        y.to_a
      else
        orig_y, y = y, Array.try_convert(y)
        if y.nil?
          raise ArgumentError, "Invalid value for y: %p" % orig_y
        end
      end

  name = []
  legend_title = []

  if color.nil?
    # TODO: do not hard code this
    line_color = Colors["#1f77b4"] # the first color of D3's category10 palette
  else
    line_color = color_mapper[color].to_rgb
    name << color
    legend_title << variables[:color]
  end

  unless style.nil?
    marker, dashes = style_mapper[style].values_at(:marker, :dashes)
    name << style
    legend_title << variables[:style]
  end

  trace = {
    type: :scatter,
    mode: marker.nil? ? "lines" : "lines+markers",
    x: x,
    y: y,
    line: {
      shape: :linear,
      color: line_color.to_hex_string
    }
  }

  default_line_width = 2.0
  unless size.nil?
    line_width = default_line_width + 2.0 * size_mapper[size]
    trace[:line][:width] = line_width
  end

  unless dashes.nil?
    trace[:line][:dash] = convert_dash_pattern(dashes, line_width || default_line_width)
  end

  unless marker.nil?
    trace[:marker] = {
      line: {
        width: 1,
        color: "#fff"
      },
      symbol: marker,
      size: 10
    }
  end

  unless ci_params.nil?
    case ci_params[:style]
    when :band
      y_min = ci_params[:y_min].to_a
      y_max = ci_params[:y_max].to_a
      @traces << {
        type: :scatter,
        x: x,
        y: y_max,
        mode: :lines,
        line: { shape: :linear, width: 0 },
        showlegend: false
      }
      @traces << {
        type: :scatter,
        x: x,
        y: y_min,
        mode: :lines,
        line: { shape: :linear, width: 0 },
        fill: :tonexty,
        fillcolor: line_color.to_rgba(alpha: 0.2).to_hex_string,
        showlegend: false
      }
    when :bars
      y_min = ci_params[:y_min].map.with_index {|v, i| y[i] - v }
      y_max = ci_params[:y_max].map.with_index {|v, i| v - y[i] }
      trace[:error_y] = {
        visible: true,
        type: :data,
        array: y_max,
        arrayminus: y_min
      }
      unless line_color.nil?
        trace[:error_y][:color] = line_color
      end
      unless line_width.nil?
        trace[:error_y][:thickness] = line_width
      end
    end
  end

  trace[:name] = name.uniq.join(", ") unless name.empty?

  @traces << trace

  unless legend_title.empty?
    @layout[:showlegend] = true
    @layout[:legend] ||= {}
    @layout[:legend][:title] = {text: legend_title.uniq.join(", ")}
  end
end

#old_style_render(context, filename) ⇒ Object



44
45
46
# File 'lib/charty/backends/plotly.rb', line 44

def old_style_render(context, filename)
  plot(nil, context)
end

#plot(plot, context) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/charty/backends/plotly.rb', line 48

def plot(plot, context)
  context = context
  self.class.chart_id += 1

  case context.method
  when :bar
    render_graph(context, :bar)
  when :curve
    render_graph(context, :scatter)
  when :scatter
    render_graph(context, nil, options: {data: {mode: "markers"}})
  else
    raise NotImplementedError
  end
end

#render(element_id: nil, format: nil, notebook: false) ⇒ Object



781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
# File 'lib/charty/backends/plotly.rb', line 781

def render(element_id: nil, format: nil, notebook: false)
  case format
  when :html, "html", nil
    format = "text/html"
  when :png, "png"
    format = "image/png"
  when :jpeg, "jpeg"
    format = "image/jpeg"
  end

  case format
  when "text/html"
    # render html after this case cause
  when "image/png", "image/jpeg"
    image_data = render_image(format, element_id: element_id, notebook: false)
    if notebook
      return [format, image_data]
    else
      return image_data
    end
  else
    raise ArgumentError,
          "Unsupported mime type to render: %p" % format
  end

  element_id = SecureRandom.uuid if element_id.nil?

  renderer = PlotlyHelpers::HtmlRenderer.new(full_html: !notebook)
  html = renderer.render({data: @traces, layout: @layout}, element_id: element_id)
  if notebook
    [format, html]
  else
    html
  end
end

#render_mimebundle(include: [], exclude: []) ⇒ Object



817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
# File 'lib/charty/backends/plotly.rb', line 817

def render_mimebundle(include: [], exclude: [])
  types = case
         when IRubyHelper.vscode?,
           IRubyHelper.nteract?
           [:plotly_mimetype]
         else
           [:plotly_mimetype, :notebook]
         end
  bundle = Util.filter_map(types) { |type|
    case type
    when :plotly_mimetype
      render_plotly_mimetype_bundle
    when :notebook
      render_notebook_bundle
    end
  }.to_h
  bundle
end

#save(filename, format: nil, title: nil, width: 700, height: 500, **kwargs) ⇒ Object



721
722
723
724
725
726
727
728
729
730
731
732
# File 'lib/charty/backends/plotly.rb', line 721

def save(filename, format: nil, title: nil, width: 700, height: 500, **kwargs)
  format = detect_format(filename) if format.nil?

  case format
  when nil, :html, "text/html"
    save_html(filename, title: title, **kwargs)
  when :png, "png", "image/png",
       :jpeg, "jpeg", "image/jpeg"
    render_image(format, filename: filename, notebook: false, title: title, width: width, height: height, **kwargs)
  end
  nil
end

#scatter(x, y, variables, color:, color_mapper:, style:, style_mapper:, size:, size_mapper:) ⇒ Object



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/charty/backends/plotly.rb', line 253

def scatter(x, y, variables, color:, color_mapper:,
            style:, style_mapper:, size:, size_mapper:)
  orig_x, orig_y = x, y

  x = case x
      when Charty::Vector
        x.to_a
      else
        Array.try_convert(x)
      end
  if x.nil?
    raise ArgumentError, "Invalid value for x: %p" % orig_x
  end

  y = case y
      when Charty::Vector
        y.to_a
      else
        Array.try_convert(y)
      end
  if y.nil?
    raise ArgumentError, "Invalid value for y: %p" % orig_y
  end

  unless color.nil? && style.nil?
    grouped_scatter(x, y, variables,
                    color: color, color_mapper: color_mapper,
                    style: style, style_mapper: style_mapper,
                    size: size, size_mapper: size_mapper)
    return
  end

  trace = {
    type: :scatter,
    mode: :markers,
    x: x,
    y: y,
    marker: {
      line: {
        width: 1,
        color: "#fff"
      },
      size: 10
    }
  }

  unless size.nil?
    trace[:marker][:size] = size_mapper[size].map {|x| 6.0 + x * 6.0 }
  end

  @traces << trace
end

#series=(series) ⇒ Object



40
41
42
# File 'lib/charty/backends/plotly.rb', line 40

def series=(series)
  @series = series
end

#set_title(title) ⇒ Object



614
615
616
617
# File 'lib/charty/backends/plotly.rb', line 614

def set_title(title)
  @layout[:title] ||= {}
  @layout[:title][:text] = title
end

#set_xlabel(label) ⇒ Object



619
620
621
622
# File 'lib/charty/backends/plotly.rb', line 619

def set_xlabel(label)
  @layout[:xaxis] ||= {}
  @layout[:xaxis][:title] = label
end

#set_xlim(min, max) ⇒ Object



653
654
655
656
# File 'lib/charty/backends/plotly.rb', line 653

def set_xlim(min, max)
  @layout[:xaxis] ||= {}
  @layout[:xaxis][:range] = [min, max]
end

#set_xscale(scale) ⇒ Object



663
664
665
666
667
# File 'lib/charty/backends/plotly.rb', line 663

def set_xscale(scale)
  scale = check_scale_type(scale, :xscale)
  @layout[:xaxis] ||= {}
  @layout[:xaxis][:type] = scale
end

#set_xtick_labels(labels) ⇒ Object



641
642
643
644
645
# File 'lib/charty/backends/plotly.rb', line 641

def set_xtick_labels(labels)
  @layout[:xaxis] ||= {}
  @layout[:xaxis][:tickmode] = "array"
  @layout[:xaxis][:ticktext] = labels
end

#set_xticks(values) ⇒ Object



629
630
631
632
633
# File 'lib/charty/backends/plotly.rb', line 629

def set_xticks(values)
  @layout[:xaxis] ||= {}
  @layout[:xaxis][:tickmode] = "array"
  @layout[:xaxis][:tickvals] = values
end

#set_ylabel(label) ⇒ Object



624
625
626
627
# File 'lib/charty/backends/plotly.rb', line 624

def set_ylabel(label)
  @layout[:yaxis] ||= {}
  @layout[:yaxis][:title] = label
end

#set_ylim(min, max) ⇒ Object



658
659
660
661
# File 'lib/charty/backends/plotly.rb', line 658

def set_ylim(min, max)
  @layout[:yaxis] ||= {}
  @layout[:yaxis][:range] = [min, max]
end

#set_yscale(scale) ⇒ Object



669
670
671
672
673
# File 'lib/charty/backends/plotly.rb', line 669

def set_yscale(scale)
  scale = check_scale_type(scale, :yscale)
  @layout[:yaxis] ||= {}
  @layout[:yaxis][:type] = scale
end

#set_ytick_labels(labels) ⇒ Object



647
648
649
650
651
# File 'lib/charty/backends/plotly.rb', line 647

def set_ytick_labels(labels)
  @layout[:yaxis] ||= {}
  @layout[:yaxis][:tickmode] = "array"
  @layout[:yaxis][:ticktext] = labels
end

#set_yticks(values) ⇒ Object



635
636
637
638
639
# File 'lib/charty/backends/plotly.rb', line 635

def set_yticks(values)
  @layout[:yaxis] ||= {}
  @layout[:yaxis][:tickmode] = "array"
  @layout[:yaxis][:tickvals] = values
end

#univariate_histogram(hist, name, variable_name, stat, alpha, color, key_color, color_mapper, _multiple, _element, _fill, _shrink) ⇒ Object



570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/charty/backends/plotly.rb', line 570

def univariate_histogram(hist, name, variable_name, stat,
                         alpha, color, key_color, color_mapper,
                         _multiple, _element, _fill, _shrink)
  value_axis = variable_name
  case value_axis
  when :x
    weights_axis = :y
    orientation = :v
  else
    weights_axis = :x
    orientation = :h
  end

  mid_points = hist.edges.each_cons(2).map {|a, b| a + (b - a) / 2 }

  trace = {
    type: :bar,
    name: name.to_s,
    value_axis => mid_points,
    weights_axis => hist.weights,
    orientation: orientation,
    opacity: alpha
  }

  if color.nil?
    trace[:marker] = {
      color: key_color.to_rgb.to_hex_string
    }
  else
    trace[:marker] = {
      color: color_mapper[color].to_rgb.to_hex_string
    }
  end

  @traces << trace

  @layout[:bargap] = 0.05

  if @traces.length > 1
    @layout[:barmode] = "overlay"
    @layout[:showlegend] = true
  end
end