Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created June 8, 2011 04:34
Show Gist options
  • Save xuwei-k/1013774 to your computer and use it in GitHub Desktop.
Save xuwei-k/1013774 to your computer and use it in GitHub Desktop.
// 折れ線グラフをScalaで出力しようとして、作りかけ(?)のもの
case class C[A](x:A,y:A)
case class LineGraph(dataAndLavel:List[(String,Int)],width:Double = 1000,height:Double = 800,color:String){
implicit def anyToString(obj:Any):String = obj.toString
def toXML:xml.Elem = {
val data = dataAndLavel.map{_._2}
val xWidtn = width / data.size
def yHeight( n:Int ) = { ( data.max - n ) / ( data.max / height ) }
val matrixs = data.zipWithIndex.map{ case (y,x) => C(x * xWidtn , yHeight( y ) ) }
val lines = matrixs.sliding(2).map{ case Seq(a,b) => line( a.x ,b.x ,a.y ,b.y ,color) }.toList
val texts = (matrixs,data).zipped.map{ ( m , s ) => text( m.x , m.y , s ) }
val backLines1 = matrixs.map{case C(x,_) => line(x,x,0,height,"gray",1) }
// val backLines2 = matrixs.map{case C(_,y) => line(0,width,y,y,"gray",1) }
val labels = (matrixs ,dataAndLavel.map{_._1}).zipped.map{ (p,str) => text( p.x , p.y - 50 , str , 18) }
wrapSVG( wrapLines ++ lines ++ texts ++ labels ++ backLines1 )
}
def save( fileName:String ){
val o = new java.io.PrintWriter( fileName,"UTF-8")
o.println( """<?xml version="1.0" encoding="UTF-8" ?>""" + toXML )
o.close
}
val wrapLines = Seq(
line(0,0,0,height,"gray",2),
line(0,width,height,height,"gray",2),
line(width,width,0,height,"gray",2),
line(0,width,0,0,"gray",2)
)
def wrapSVG(e:xml.NodeSeq) = {
val margin = 100
val box = Seq( - margin , - margin , width + margin , height + margin ).mkString(" ")
<svg xmlns="http://www.w3.org/2000/svg" viewBox={box}>{e}</svg>
}
def line(x1:Double,x2:Double,y1:Double,y2:Double,color:String = "black" ,width:Int = 5 ):xml.Elem = {
<line y1={y1} x1={x1} stroke={color} stroke-width={width} x2={x2} y2={y2} ></line>
}
def text(x:Double,y:Double,str:String , fontSize:Int=30):xml.Elem = {
<text y={y} x={x} font-size={fontSize} >{ str }</text>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment