Class: Charty::Backends::Pyplot

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

Constant Summary collapse

PYPLOT_MARKERS =
{
         circle: "o",
              x: "X",
          cross: "P",
    triangle_up: "^",
  triangle_down: "v",
         square: [4, 0, 45].freeze,
        diamond: [4, 0, 0].freeze,
           star: [5, 1, 0].freeze,
   star_diamond: [4, 1, 0].freeze,
    star_square: [4, 1, 45].freeze,
       pentagon: [5, 0, 0].freeze,
        hexagon: [6, 0, 0].freeze,
}.freeze
RELATIONAL_PLOT_LEGEND_BRIEF_TICKS =
6
SAVEFIG_OPTIONAL_PARAMS =
[
  :dpi, :quality, :optimize, :progressive, :facecolor, :edgecolor,
  :orientation, :papertype, :transparent, :bbox_inches, :pad_inches,
  :bbox_extra_artists, :backend, :metadata, :pil_kwargs
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePyplot

Returns a new instance of Pyplot.



15
16
17
18
19
20
# File 'lib/charty/backends/pyplot.rb', line 15

def initialize
  @pyplot = ::Matplotlib::Pyplot
  @default_edgecolor = Colors["white"].to_rgb
  @default_line_width = ::Matplotlib.rcParams["lines.linewidth"]
  @default_marker_size = ::Matplotlib.rcParams["lines.markersize"]
end

Class Method Details

.activate_iruby_integrationObject



22
23
24
25
# File 'lib/charty/backends/pyplot.rb', line 22

def self.activate_iruby_integration
  require 'matplotlib/iruby'
  ::Matplotlib::IRuby.activate
end

.prepareObject



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

def prepare
  require 'matplotlib/pyplot'
  require 'numpy'
end

Instance Method Details

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



561
562
563
564
565
566
567
568
569
# File 'lib/charty/backends/pyplot.rb', line 561

def add_line_plot_legend(variables, color_mapper, size_mapper, style_mapper, legend)
  ax = @pyplot.gca
  add_relational_plot_legend(
    ax, variables, color_mapper, size_mapper, style_mapper,
    legend, [:color, :linewidth, :marker, :dashes]
  ) do |label, kwargs|
    ax.plot([], [], label: label, **kwargs)
  end
end

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



334
335
336
337
338
339
340
341
342
# File 'lib/charty/backends/pyplot.rb', line 334

def add_scatter_plot_legend(variables, color_mapper, size_mapper, style_mapper, legend)
  ax = @pyplot.gca
  add_relational_plot_legend(
    ax, variables, color_mapper, size_mapper, style_mapper,
    legend, [:color, :s, :marker]
  ) do |label, kwargs|
    ax.scatter([], [], label: label, **kwargs)
  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



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/charty/backends/pyplot.rb', line 148

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)
  width = Float(width)

  ax = @pyplot.gca
  kw = {color: colors, align: align}
  kw[:label] = label unless label.nil?

  if orient == :v
    ax.bar(bar_pos, values, width, **kw)
  else
    ax.barh(bar_pos, values, width, **kw)
  end

  if conf_int
    error_colors = Array(error_colors).map(&:to_hex_string)
    confidence_intervals(ax, bar_pos, conf_int, orient, error_colors, error_width, cap_size)
  end
end

#begin_figureObject

NEW PLOTTING API ====



143
144
145
146
# File 'lib/charty/backends/pyplot.rb', line 143

def begin_figure
  @legend_keys = []
  @legend_labels = []
end

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



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/charty/backends/pyplot.rb', line 195

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(flier_size)
  whisker = Float(whisker)

  plot_data.each_with_index do |group_data, i|
    unless group_data.nil?
      draw_box_plot(group_data,
                    vert: (orient == :v),
                    position: i,
                    color: colors[i],
                    gray: gray,
                    width: width,
                    whisker: whisker,
                    flier_size: flier_size)
    end
  end
end

#disable_xaxis_gridObject



722
723
724
# File 'lib/charty/backends/pyplot.rb', line 722

def disable_xaxis_grid
  @pyplot.gca.xaxis.grid(false)
end

#disable_yaxis_gridObject



726
727
728
# File 'lib/charty/backends/pyplot.rb', line 726

def disable_yaxis_grid
  @pyplot.gca.xaxis.grid(false)
end

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



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
# File 'lib/charty/backends/pyplot.rb', line 218

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(flier_size)
  whisker = Float(whisker)

  offsets = color_offsets(color_names, dodge, width)
  orig_width = width
  width = Float(nested_width(color_names, dodge, width))

  color_names.each_with_index do |color_name, i|
    add_box_plot_legend(gray, colors[i], color_names[i])

    plot_data[i].each_with_index do |group_data, j|
      next if group_data.empty?

      position = j + offsets[i]
      draw_box_plot(group_data,
                    vert: (orient == :v),
                    position: position,
                    color: colors[i],
                    gray: gray,
                    width: width,
                    whisker: whisker,
                    flier_size: flier_size)
    end
  end
end

#invert_yaxisObject



730
731
732
# File 'lib/charty/backends/pyplot.rb', line 730

def invert_yaxis
  @pyplot.gca.invert_yaxis
end

#label(x, y) ⇒ Object



27
28
# File 'lib/charty/backends/pyplot.rb', line 27

def label(x, y)
end

#legend(loc:, title:) ⇒ Object



734
735
736
# File 'lib/charty/backends/pyplot.rb', line 734

def legend(loc:, title:)
  @pyplot.gca.legend(loc: loc, title: title)
end

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



498
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
551
552
553
554
555
556
557
558
559
# File 'lib/charty/backends/pyplot.rb', line 498

def line(x, y, variables, color:, color_mapper:, size:, size_mapper:, style:, style_mapper:, ci_params:)
  kws = {
    markeredgewidth: 0.75,
    markeredgecolor: "w",
  }
  ax = @pyplot.gca

  x = x.to_a
  y = y.to_a
  lines = ax.plot(x, y, **kws)

  lines.each do |line|
    unless color.nil?
      line.set_color(color_mapper[color].to_rgb.to_hex_string)
    end

    unless size.nil?
      scaled_size = scale_line_width(size_mapper[size])
      line.set_linewidth(scaled_size.to_f)
    end

    unless style.nil?
      attributes = style_mapper[style]
      if attributes.key?(:dashes)
        line.set_dashes(attributes[:dashes])
      end
      if attributes.key?(:marker)
        line.set_marker(PYPLOT_MARKERS[attributes[:marker]])
      end
    end
  end

  # TODO: support color, size, and style

  line = lines[0]
  line_color = line.get_color
  line_alpha = line.get_alpha
  line_capstyle = line.get_solid_capstyle

  unless ci_params.nil?
    y_min = ci_params[:y_min].to_a
    y_max = ci_params[:y_max].to_a
    case ci_params[:style]
    when :band
      # TODO: support to supply `alpha` via `err_kws`
      ax.fill_between(x, y_min, y_max, color: line_color, alpha: 0.2)
    when :bars
      error_deltas = [
        y.zip(y_min).map {|v, v_min| v - v_min },
        y.zip(y_max).map {|v, v_max| v_max - v }
      ]
      ebars = ax.errorbar(x, y, error_deltas,
                          linestyle: "", color: line_color, alpha: line_alpha)
      ebars.get_children.each do |bar|
        case bar
        when Matplotlib.collections.LineCollection
          bar.set_capstyle(line_capstyle)
        end
      end
    end
  end
end

#old_style_render(context, filename) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/charty/backends/pyplot.rb', line 45

def old_style_render(context, filename)
  plot(@pyplot, context)
  if filename
    FileUtils.mkdir_p(File.dirname(filename))
    @pyplot.savefig(filename)
  end
  @pyplot.show
end

#old_style_save(context, filename, finish: true) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/charty/backends/pyplot.rb', line 54

def old_style_save(context, filename, finish: true)
  plot(context)
  if filename
    FileUtils.mkdir_p(File.dirname(filename))
    @pyplot.savefig(filename)
  end
  @pyplot.clf if finish
end

#plot(ax, context, subplot: false) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/charty/backends/pyplot.rb', line 63

def plot(ax, context, subplot: false)
  # TODO: Since it is not required, research and change conditions.
  # case
  # when @pyplot.respond_to?(:xlim)
  #   @pyplot.xlim(context.range_x.begin, context.range_x.end)
  #   @pyplot.ylim(context.range_y.begin, context.range_y.end)
  # when @pyplot.respond_to?(:set_xlim)
  #   @pyplot.set_xlim(context.range_x.begin, context.range_x.end)
  #   @pyplot.set_ylim(context.range_y.begin, context.range_y.end)
  # end

  ax.title(context.title) if context.title
  if !subplot
    ax.xlabel(context.xlabel) if context.xlabel
    ax.ylabel(context.ylabel) if context.ylabel
  end

  palette = Palette.default
  colors = palette.colors.map {|c| c.to_rgb.to_hex_string }.cycle
  case context.method
  when :bar
    context.series.each do |data|
      ax.bar(data.xs.to_a.map(&:to_s), data.ys.to_a, label: data.label,
             color: colors.next)
    end
    ax.legend()
  when :barh
    context.series.each do |data|
      ax.barh(data.xs.to_a.map(&:to_s), data.ys.to_a, color: colors.next)
    end
  when :box_plot
    min_l = palette.colors.map {|c| c.to_rgb.to_hsl.l }.min
    lum = min_l*0.6
    gray = Colors::RGB.new(lum, lum, lum).to_hex_string
    Array(context.data).each_with_index do |group_data, i|
      next if group_data.empty?

      box_data = group_data.compact
      next if box_data.empty?

      color = colors.next
      draw_box_plot(box_data, vert: "v", position: i, color: color,
                    gray: gray, width: 0.8, whisker: 1.5, flier_size: 5)
    end
  when :bubble
    context.series.each do |data|
      ax.scatter(data.xs.to_a, data.ys.to_a, s: data.zs.to_a, alpha: 0.5,
                 color: colors.next, label: data.label)
    end
    ax.legend()
  when :curve
    context.series.each do |data|
      ax.plot(data.xs.to_a, data.ys.to_a, color: colors.next)
    end
  when :scatter
    context.series.each do |data|
      ax.scatter(data.xs.to_a, data.ys.to_a, label: data.label,
                 color: colors.next)
    end
    ax.legend()
  when :error_bar
    context.series.each do |data|
      ax.errorbar(
        data.xs.to_a,
        data.ys.to_a,
        data.xerr,
        data.yerr,
        label: data.label,
        color: colors.next
      )
    end
    ax.legend()
  when :hist
    data = Array(context.data)
    ax.hist(data, color: colors.take(data.length), alpha: 0.4)
  end
end

#render(notebook: false) ⇒ Object



738
739
740
741
# File 'lib/charty/backends/pyplot.rb', line 738

def render(notebook: false)
  show
  nil
end

#render_layout(layout) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/charty/backends/pyplot.rb', line 34

def render_layout(layout)
  _fig, axes = @pyplot.subplots(nrows: layout.num_rows, ncols: layout.num_cols)
  layout.rows.each_with_index do |row, y|
    row.each_with_index do |cel, x|
      ax = layout.num_rows > 1 ? axes[y][x] : axes[x]
      plot(ax, cel, subplot: true)
    end
  end
  @pyplot.show
end

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



743
744
745
746
# File 'lib/charty/backends/pyplot.rb', line 743

def render_mimebundle(include: [], exclude: [])
  show
  {}
end

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



754
755
756
757
758
759
760
761
762
# File 'lib/charty/backends/pyplot.rb', line 754

def save(filename, format: nil, title: nil, width: 700, height: 500, **kwargs)
  params = {}
  params[:format] = format unless format.nil?
  SAVEFIG_OPTIONAL_PARAMS.each do |key|
    params[key] = kwargs[key] if kwargs.key?(key)
  end
  @pyplot.savefig(filename, **params)
  @pyplot.close
end

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



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/charty/backends/pyplot.rb', line 307

def scatter(x, y, variables, color:, color_mapper:,
            style:, style_mapper:, size:, size_mapper:)
  kwd = {}
  kwd[:edgecolor] = "w"

  ax = @pyplot.gca
  points = ax.scatter(x.to_a, y.to_a, **kwd)

  unless color.nil?
    color = color_mapper[color].map(&:to_hex_string)
    points.set_facecolors(color)
  end

  unless size.nil?
    size = size_mapper[size].map {|x| scale_scatter_point_size(x).to_f }
    points.set_sizes(size)
  end

  unless style.nil?
    paths = style_mapper[style, :marker].map(&method(:marker_to_path))
    points.set_paths(paths)
  end

  sizes = points.get_sizes
  points.set_linewidths(0.08 * Numpy.sqrt(Numpy.percentile(sizes, 10)))
end

#series=(series) ⇒ Object



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

def series=(series)
  @series = series
end

#set_title(title) ⇒ Object



665
666
667
# File 'lib/charty/backends/pyplot.rb', line 665

def set_title(title)
  @pyplot.gca.set_title(String(title))
end

#set_xlabel(label) ⇒ Object



669
670
671
# File 'lib/charty/backends/pyplot.rb', line 669

def set_xlabel(label)
  @pyplot.gca.set_xlabel(String(label))
end

#set_xlim(min, max) ⇒ Object



693
694
695
# File 'lib/charty/backends/pyplot.rb', line 693

def set_xlim(min, max)
  @pyplot.gca.set_xlim(Float(min), Float(max))
end

#set_xscale(scale) ⇒ Object



701
702
703
704
# File 'lib/charty/backends/pyplot.rb', line 701

def set_xscale(scale)
  scale = check_scale_type(scale, :xscale)
  @pyplot.gca.set_xscale(scale)
end

#set_xtick_labels(labels) ⇒ Object



685
686
687
# File 'lib/charty/backends/pyplot.rb', line 685

def set_xtick_labels(labels)
  @pyplot.gca.set_xticklabels(Array(labels).map(&method(:String)))
end

#set_xticks(values) ⇒ Object



677
678
679
# File 'lib/charty/backends/pyplot.rb', line 677

def set_xticks(values)
  @pyplot.gca.set_xticks(Array(values))
end

#set_ylabel(label) ⇒ Object



673
674
675
# File 'lib/charty/backends/pyplot.rb', line 673

def set_ylabel(label)
  @pyplot.gca.set_ylabel(String(label))
end

#set_ylim(min, max) ⇒ Object



697
698
699
# File 'lib/charty/backends/pyplot.rb', line 697

def set_ylim(min, max)
  @pyplot.gca.set_ylim(Float(min), Float(max))
end

#set_yscale(scale) ⇒ Object



706
707
708
709
# File 'lib/charty/backends/pyplot.rb', line 706

def set_yscale(scale)
  scale = check_scale_type(scale, :yscale)
  @pyplot.gca.set_yscale(scale)
end

#set_ytick_labels(labels) ⇒ Object



689
690
691
# File 'lib/charty/backends/pyplot.rb', line 689

def set_ytick_labels(labels)
  @pyplot.gca.set_yticklabels(Array(labels).map(&method(:String)))
end

#set_yticks(values) ⇒ Object



681
682
683
# File 'lib/charty/backends/pyplot.rb', line 681

def set_yticks(values)
  @pyplot.gca.set_yticks(Array(values))
end

#showObject



764
765
766
# File 'lib/charty/backends/pyplot.rb', line 764

def show
  @pyplot.show
end

#univariate_histogram(hist, name, variable_name, stat, alpha, color, key_color, color_mapper, multiple, element, fill, shrink) ⇒ Object



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
613
614
615
616
617
618
# File 'lib/charty/backends/pyplot.rb', line 579

def univariate_histogram(hist, name, variable_name, stat,
                         alpha, color, key_color, color_mapper,
                         multiple, element, fill, shrink)
  mid_points = hist.edges.each_cons(2).map {|a, b| a + (b - a) / 2 }
  orient = variable_name == :x ? :v : :h
  width = shrink * (hist.edges[1] - hist.edges[0])

  kw = {align: :edge}

  color = if color.nil?
            key_color.to_rgb
          else
            color_mapper[color].to_rgb
          end

  alpha = 1r unless fill

  if fill
    kw[:facecolor] = color.to_rgba(alpha: alpha).to_hex_string
    if multiple == :stack || multiple == :fill || element == :bars
      kw[:edgecolor] = @default_edgecolor.to_hex_string
    else
      kw[:edgecolor] = color.to_hex_string
    end
  elsif element == :bars
    kw.delete(:facecolor)
    kw[:edgecolor] = color.to_rgba(alpha: alpha).to_hex_string
  else
    kw[:color] = color.to_rgba(alpha: alpha).to_hex_string
  end

  kw[:label] = name unless name.nil?

  ax = @pyplot.gca
  if orient == :v
    ax.bar(mid_points, hist.weights, width, **kw)
  else
    ax.barh(mid_points, hist.weights, width, **kw)
  end
end