Graphical Dots and Rectangles in Ruby

I am looking for an easy way to build about 10 points and rectangles to see where my algorithm goes wrong. I looked at gnuplot, but it seems like especially bad rectangles to build.

+7
source share
2 answers

SVG ( MDN Tutorial ) is a very simple text format (XML) that you can easily generate using Ruby without any SVG library and view it in any modern web browser. Here is one example:

SVG points through line interpolation

points = (0..5).map{ [rand(100)-50,rand(100)-50] } puts <<ENDSVG <svg xmlns="http://www.w3.org/2000/svg" viewBox="-100 -100 200 200"> #{points.map{ |x,y| "<circle cx='#{x}' cy='#{y}' r='3' />" }.join("\n")} </svg> ENDSVG 

Exit: http://jsfiddle.net/xwnVY/


If you want to be more structured than string interpolation:

SVG Points Using Nokogiri XML-Builder

 require 'nokogiri' # gem install nokogiri b = Nokogiri::XML::Builder.new do |doc| doc.svg xmlns:"http://www.w3.org/2000/svg", viewBox:"-100 -100 200 200" do points.each do |x,y| doc.circle r:3, cx:x, cy:y end end end puts b.to_xml 

Save the output as "foo.svg" and open it in a modern web browser for viewing.


Drawing

To draw rectangles, you can use any of:

 <rect transform="rotate(45)" x="0" y="0" width="100" height="200" /> <polygon points="0,0 100,0 100,100 0,100" /> <path d="M0,0 L100,0 100,100 0,100 Z" /> 

A polygon can be the easiest to create if you want to connect arbitrary points that are not oriented along the axes without worrying about transformations. Please note that while I have clearly shown the coordinates above in the format x,yx,y , SVG will also take x,y,x,y or xyxy if these files are easier to create.


Format bit

If you want to draw outlines instead of filled shapes, you can add this CSS to your SVG:

 <style> rect, polygon, path { fill:none; stroke:black; stroke-width:1px } </style> 

Using Haml for XML

Finally, Haml is another option that you might consider creating your XML without the SVG library:

 @points = (0..7).map{ [rand(100)-50,rand(100)-50] } require 'haml' puts Haml::Engine.new(<<ENDHAML).render(self) %svg(xmlns="http://www.w3.org/2000/svg" viewBox="-100 -100 200 200") :css circle { fill:orange } rect, polygon, path { fill:none; stroke:black; vector-effect:non-scaling-stroke } - @points.each_slice(4) do |rect| %polygon{ points:rect.join(" ") } - @points.each do |x,y| %circle{r:3, cx:x, cy:y} ENDHAML 

Exit: http://jsfiddle.net/xwnVY/4/

+14
source

Perhaps you can try SVG. Easy to create (simple XML), open, cross-platform, you can open it and edit using Inkscape, etc.

+4
source

All Articles