14
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

レインボーをn分割した16進数rgb色コードを出力

Last updated at Posted at 2013-03-25

データの可視化をするのにレインボーカラーチャートで色づけしてプロットできると見やすいので、レインボーカラーチャートをn分割して16進数rgb色コードを出力するコードを備忘録がてらシェア。こんなかんじ。

Terminal 出力

引数はデータ総数n(=分割数)。コードは以下の通り。まんまなので、エレガントなやり方あれば教えてください。

color.rb
#!/usr/bin/env ruby
require "rubygems"
require 'paint'

class Integer
   def color(max)
      h = Array.new
      sg = 256*6/(max)*(self)
      if sg >= 0 && sg <=(256*1-1) then
         h[0] = "ff"
         h[1] =  ("%02x" % sg)
         h[2] = "00"
      elsif sg > (256*1-1) && sg <= (256*2-1) then
         h[0] = ("%02x" %(256*2-1-sg))
         h[1] = "ff"
         h[2] = "00"
      elsif sg > (256*2-1) && sg <= (256*3-1) then
         h[0] = "00"
         h[1] = "ff"
         h[2] = ("%02x" % (sg-256*2))
      elsif sg > (256*3-1) && sg <= (256*4-1) then
         h[0] = "00"
         h[1] = ("%02x" %(256*4-1-sg))
         h[2] = "ff"
      elsif sg > (256*4-1) && sg <= (256*5-1) then
         h[0] = ("%02x" % (sg-256*4))
         h[1] = "00"
         h[2] = "ff"
      elsif sg > (256*5-1) && sg <= (256*6-1) then
         h[0] = "ff"
         h[1] = "00"
         h[2] = ("%02x" %(256*6-1-sg))
      end
      return h[2]+h[1]+h[0]
   end
end

imax = ARGV[0].to_i
imax.times do |i|
   print Paint["##{i.color(imax)}", "##{i.color(imax)}"]
end
print "\n"

たとえば、gnuplotなんかでプロットする場合は、次のようになる。
Gnuplot 出力

rubyから直接gnuplotを描く場合、open3などでgnuplotに命令を流し込んで、plot命令にlc rgb "#{i.color(imax)}"として色を指定すればOK。たとえば

color_gnuplot(partial).rb
plot_str =""
plot_str << "plot"
imax = 30
imax.times do |i|
   plot_str << " 100*exp(-(x/4)**2)+#{i}+20*exp(-((x-10)/2)**2)+#{i} "
   plot_str << "w l lt 10 lc rgb \"##{i.color(imax)}\" t \"\","
end
plot_str = plot_str[0, plot_str.length-1]

Open3.popen3("gnuplot"){|stdin, stdout, stderr|
   stdin.puts <<-"EOS"
   set output
   set clip one
   set ytics nomirror
   set ylabel "Amplitude [a.u.]" 2,0
   set xlabel "Frequency [Hz]"
   set yrange[*:*]
   set xrange[*:20]
   set size 0.5, 0.5
   set pointsize 1.2
   unset key
   set output "./fig.eps"
   set terminal postscript eps enhanced color
   #{plot_str}
   set output
   EOS
   stdin.close
   end
   printf("%s",stdout.read)
}
14
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?