Search code examples
scalaplotjfreechart

Plot scala arrays with jfreechart


I have 2 scala array and I would like to plot them as an x,y plot.

I have heard that jfreechart is a good choice for plotting in scala. I think that the right command to plot them is XYPlot but how can I use it?

  val x = Array(1,2,3,4,5,6,7,8,9,10)
    val y = x.map(_*2)
import org.jfree.chart.plot.XYPlot

with python matplotlib I would have just used plot(x,y)


Solution

  • You'll need to put your data into a DataSet and then use a ChartFrame to display the chart.

    import org.jfree.chart._
    import org.jfree.data.xy._
    
    val x = Array[Double](1,2,3,4,5,6,7,8,9,10)
    val y = x.map(_*2)
    val dataset = new DefaultXYDataset
    dataset.addSeries("Series 1",Array(x,y))
    
    val frame = new ChartFrame(
      "Title",
      ChartFactory.createScatterPlot(
        "Plot",
        "X Label",
        "Y Label",
        dataset,
        org.jfree.chart.plot.PlotOrientation.HORIZONTAL,
        false,false,false
      )
    )
    frame.pack()
    frame.setVisible(true)