Skip to content

Instantly share code, notes, and snippets.

@rinx
Created February 6, 2016 06:32
Show Gist options
  • Save rinx/e964b7f0142bb26a615a to your computer and use it in GitHub Desktop.
Save rinx/e964b7f0142bb26a615a to your computer and use it in GitHub Desktop.
gnuplot gem heatmap test
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
#
# plot-3d-ipa.rb
#
# Author:
# Rintaro Okamura
#
# Requires ruby-netcdf
# https://www.gfd-dennou.org/arch/ruby/products/ruby-netcdf/
#
# Usage:
# $ ruby plot-3d-ipa.rb ncfile1 ncfile2 x y output
#
# Changelog:
# 20160125 - First version
#
require 'narray'
require 'gnuplot'
require 'optparse'
# https://github.com/rdp/ruby_gnuplot/blob/master/lib/gnuplot.rb#L358
class SPlot < Gnuplot::Plot
def initialize (io = nil, cmd = "splot")
@cmd = cmd
@settings = []
@arbitrary_lines = []
@data = []
@styles = []
yield self if block_given?
$stderr.puts "writing this to gnuplot:\n" + to_gsplot + "\n" if $VERBOSE
if io
io << to_gsplot
io << store_datasets
end
end
def to_gsplot (io = "")
@settings.each do |setting|
io << setting.map(&:to_s).join(" ") << "\n"
end
@styles.each{|s| io << s.to_s << "\n"}
@arbitrary_lines.each{|line| io << line << "\n" }
io
end
def store_datasets (io = "")
if @data.size > 0
io << @cmd << " " << @data.collect { |e| e.plot_args }.join(", ")
io << "\n"
v = @data.collect { |ds| ds.to_gsplot }
io << v.compact.join("e\n")
end
end
end
class Array
def to_gsplot
f = ""
if ( self[0].kind_of? Array ) then
x = self[0]
y = self[1]
d = self[2]
x.each_with_index do |xv, i|
y.each_with_index do |yv, j|
f << [ xv, yv, d[i][j] ].join(" ") << "\n"
end
f << "\n"
end
elsif ( self[0].kind_of? Numeric ) then
self.length.times do |i| f << "#{self[i]}\n" end
else
self[0].zip( *self[1..-1] ).to_gsplot
end
f
end
end
nx=5
ny=5
outfile="test.png"
# generate index
x = [*1..nx]
y = [*1..ny]
cot_2d = NArray.sfloat(nx, ny)
cot_2d.indgen(1)
puts cot_2d.to_a
cot_2d_arr = cot_2d[true,true].to_a.transpose
maxval = cot_2d_arr.flatten.max
Gnuplot.open do |gp|
SPlot.new(gp) do |plot|
case outfile
when /^none$/
plot.terminal 'x11'
when /\.tex$/
plot.terminal "tikz"
plot.output File.expand_path(outfile.gsub(/\.tex$/, '_cot.tex'))
when /\.pdf$/
plot.terminal "pdf font 'Helvetica,7'"
plot.output File.expand_path(outfile.gsub(/\.pdf$/, '_cot.pdf'))
when /\.png$/
plot.terminal "pngcairo"
plot.output File.expand_path(outfile.gsub(/\.png$/, '_cot.png'))
else
STDERR.puts "Error: unknown filetype"
exit
end
plot.set "termoption noenhanced"
plot.title "Cloud Optical Thickness"
plot.xlabel "x"
plot.ylabel "y"
plot.cblabel "Optical Thickness"
plot.set "view map"
plot.set "size square"
plot.xrange "[0.5:#{nx}.5]"
plot.yrange "[0.5:#{ny}.5]"
plot.cbrange "[0:#{maxval}]"
plot.set "key off"
plot.set "palette defined ( 0 0 0 0, 1 1 1 1 )"
plot.data <<
Gnuplot::DataSet.new([x, y, cot_2d_arr]) do |ds|
ds.with = "image"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment