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

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

Class Method Details

.activate_iruby_integrationObject



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

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



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

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



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

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



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

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 ====



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

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



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

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



655
656
657
# File 'lib/charty/backends/pyplot.rb', line 655

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

#disable_yaxis_gridObject



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

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



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

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



663
664
665
# File 'lib/charty/backends/pyplot.rb', line 663

def invert_yaxis
  @pyplot.gca.invert_yaxis
end

#label(x, y) ⇒ Object



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

def label(x, y)
end

#legend(loc:, title:) ⇒ Object



667
668
669
# File 'lib/charty/backends/pyplot.rb', line 667

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



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

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



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

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



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

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



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

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



671
672
673
# File 'lib/charty/backends/pyplot.rb', line 671

def render(notebook: false)
  show
end

#render_layout(layout) ⇒ Object



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

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

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



681
682
683
684
685
686
687
688
# File 'lib/charty/backends/pyplot.rb', line 681

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)
end

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



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

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



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

def series=(series)
  @series = series
end

#set_xlabel(label) ⇒ Object



623
624
625
# File 'lib/charty/backends/pyplot.rb', line 623

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

#set_xlim(min, max) ⇒ Object



647
648
649
# File 'lib/charty/backends/pyplot.rb', line 647

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

#set_xtick_labels(labels) ⇒ Object



639
640
641
# File 'lib/charty/backends/pyplot.rb', line 639

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

#set_xticks(values) ⇒ Object



631
632
633
# File 'lib/charty/backends/pyplot.rb', line 631

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

#set_ylabel(label) ⇒ Object



627
628
629
# File 'lib/charty/backends/pyplot.rb', line 627

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

#set_ylim(min, max) ⇒ Object



651
652
653
# File 'lib/charty/backends/pyplot.rb', line 651

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

#set_ytick_labels(labels) ⇒ Object



643
644
645
# File 'lib/charty/backends/pyplot.rb', line 643

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

#set_yticks(values) ⇒ Object



635
636
637
# File 'lib/charty/backends/pyplot.rb', line 635

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

#showObject



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

def show
  @pyplot.show
end