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

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

#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



579
580
581
# File 'lib/charty/backends/pyplot.rb', line 579

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

#disable_yaxis_gridObject



583
584
585
# File 'lib/charty/backends/pyplot.rb', line 583

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



587
588
589
# File 'lib/charty/backends/pyplot.rb', line 587

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



591
592
593
# File 'lib/charty/backends/pyplot.rb', line 591

def legend(loc:, title:)
  @pyplot.gca.legend(loc: loc, title: title)
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(context, filename) ⇒ Object



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

def render(context, filename)
  plot(@pyplot, context)
  if filename
    FileUtils.mkdir_p(File.dirname(filename))
    @pyplot.savefig(filename)
  end
  @pyplot.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(context, filename, finish: true) ⇒ Object



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

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

#scatter(x, y, variables, legend:, 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
332
333
334
335
336
337
338
339
340
# File 'lib/charty/backends/pyplot.rb', line 306

def scatter(x, y, variables, legend:, 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(&method(:scale_scatter_point_size))
    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)))

  if legend
    add_relational_plot_legend(
      ax, legend, variables, color_mapper, size_mapper, style_mapper,
      [:color, :s, :marker]
    ) do |label, kwargs|
      ax.scatter([], [], label: label, **kwargs)
    end
  end
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



547
548
549
# File 'lib/charty/backends/pyplot.rb', line 547

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

#set_xlim(min, max) ⇒ Object



571
572
573
# File 'lib/charty/backends/pyplot.rb', line 571

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

#set_xtick_labels(labels) ⇒ Object



563
564
565
# File 'lib/charty/backends/pyplot.rb', line 563

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

#set_xticks(values) ⇒ Object



555
556
557
# File 'lib/charty/backends/pyplot.rb', line 555

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

#set_ylabel(label) ⇒ Object



551
552
553
# File 'lib/charty/backends/pyplot.rb', line 551

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

#set_ylim(min, max) ⇒ Object



575
576
577
# File 'lib/charty/backends/pyplot.rb', line 575

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

#set_ytick_labels(labels) ⇒ Object



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

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

#set_yticks(values) ⇒ Object



559
560
561
# File 'lib/charty/backends/pyplot.rb', line 559

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

#showObject



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

def show
  @pyplot.show
end