Class: Charty::Backends::Plotly

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

Defined Under Namespace

Modules: IRubyOutput Classes: HTML

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.chart_idObject



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

def chart_id
  @chart_id ||= 0
end

.plotly_srcObject



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

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

.with_api_load_tagObject



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

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.



10
11
12
# File 'lib/charty/backends/plotly.rb', line 10

def context
  @context
end

Class Method Details

.ensure_playwrightObject



820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/charty/backends/plotly.rb', line 820

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

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



868
869
870
871
# File 'lib/charty/backends/plotly.rb', line 868

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



860
861
862
863
864
# File 'lib/charty/backends/plotly.rb', line 860

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



499
500
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
# File 'lib/charty/backends/plotly.rb', line 499

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



363
364
365
366
367
# File 'lib/charty/backends/plotly.rb', line 363

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



125
126
127
128
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
# File 'lib/charty/backends/plotly.rb', line 125

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
    x = group_names unless group_names.nil?
  else
    x, y = values, bar_pos
    y = group_names unless group_names.nil?
  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



120
121
122
123
# File 'lib/charty/backends/plotly.rb', line 120

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



175
176
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
# File 'lib/charty/backends/plotly.rb', line 175

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



605
606
607
# File 'lib/charty/backends/plotly.rb', line 605

def disable_xaxis_grid
  # do nothing
end

#disable_yaxis_gridObject



609
610
611
# File 'lib/charty/backends/plotly.rb', line 609

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



206
207
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
# File 'lib/charty/backends/plotly.rb', line 206

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)
    else
      trace.update(x: values, y: group_keys)
    end

    trace
  end

  @traces.concat(traces)
end

#initilizeObject



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

def initilize
end

#invert_yaxisObject



613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'lib/charty/backends/plotly.rb', line 613

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



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

def label(x, y)
end

#legend(loc:, title:) ⇒ Object



630
631
632
633
634
635
636
637
638
# File 'lib/charty/backends/plotly.rb', line 630

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



376
377
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
# File 'lib/charty/backends/plotly.rb', line 376

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



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

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

#plot(plot, context) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/charty/backends/plotly.rb', line 44

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



700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# File 'lib/charty/backends/plotly.rb', line 700

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

  case format
  when "text/html", nil
    # 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

  # TODO: size should be customizable
  html = <<~HTML
    <div id="%{id}" style="width: 100%%; height:525px;"></div>
    <script type="text/javascript">
      requirejs(["plotly"], function (Plotly) {
        Plotly.newPlot("%{id}", %{data}, %{layout});
      });
    </script>
  HTML

  element_id = SecureRandom.uuid if element_id.nil?

  html %= {
    id: element_id,
    data: JSON.dump(@traces),
    layout: JSON.dump(@layout)
  }

  if notebook
    IRubyOutput.prepare
    ["text/html", html]
  else
    html
  end
end

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



640
641
642
643
644
645
646
647
648
649
650
651
# File 'lib/charty/backends/plotly.rb', line 640

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



251
252
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
# File 'lib/charty/backends/plotly.rb', line 251

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



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

def series=(series)
  @series = series
end

#set_xlabel(label) ⇒ Object



561
562
563
564
# File 'lib/charty/backends/plotly.rb', line 561

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

#set_xlim(min, max) ⇒ Object



595
596
597
598
# File 'lib/charty/backends/plotly.rb', line 595

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

#set_xtick_labels(labels) ⇒ Object



583
584
585
586
587
# File 'lib/charty/backends/plotly.rb', line 583

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

#set_xticks(values) ⇒ Object



571
572
573
574
575
# File 'lib/charty/backends/plotly.rb', line 571

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

#set_ylabel(label) ⇒ Object



566
567
568
569
# File 'lib/charty/backends/plotly.rb', line 566

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

#set_ylim(min, max) ⇒ Object



600
601
602
603
# File 'lib/charty/backends/plotly.rb', line 600

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

#set_ytick_labels(labels) ⇒ Object



589
590
591
592
593
# File 'lib/charty/backends/plotly.rb', line 589

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

#set_yticks(values) ⇒ Object



577
578
579
580
581
# File 'lib/charty/backends/plotly.rb', line 577

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