Jacob
Jacob

Reputation: 3801

Scala-Chart histrogram with multiple bars per bin

I need to create a Histogram in Scala and I need to create two series in one chart which is distrubuted into 5 bins. I've found a library scala-chart which is a wrapper around jFreeChart. I can create a histrogram dataset add two series and make a chart just fine as so:

  val data:HistogramDataset = new HistogramDataset
  data.addSeries("Class 0",class0,5)
  data.addSeries("Class 1",class1,5)

  val chart = ChartFactories.XYBarChart(class1data)

However the two bars simply overlap so I can't see much information. There is a jFreeChart class that seems to be able to do the job: ClusteredXYBarRenderer, but how do I use this to draw my chart?


As a bonus question, is there anyway to make it show the different distributions in percent instead of simply showing them as a number of how many values there are in each bin?

Ideally I'm looking for a final product like this: enter image description here

Upvotes: 2

Views: 2077

Answers (1)

0__
0__

Reputation: 67300

Have you look at this example. It uses the DefaultCategoryDataset, where categories = bins. You could use scala-chart's toCategoryDataset for a Tuple3 with (count, series, bin). But it is a little complicated to order the data correctly. I have found that in many cases it is indeed easier to construct the datasets using the default Java API instead of the to... methods of scala-chart.

import scalax.chart._

val ds = new org.jfree.data.category.DefaultCategoryDataset
ds.addValue(5, "Class A", "Bin 1")
ds.addValue(7, "Class A", "Bin 2")
ds.addValue(8, "Class B", "Bin 1")
ds.addValue(3, "Class B", "Bin 2")

val chart = ChartFactories.BarChart(ds)
chart.show()

enter image description here

To use percentages, the simplest is to provide the values already translated into percent. Otherwise you would need to change the axis tick label renderer.

Upvotes: 2

Related Questions