Search code examples
clojurejfreechartincanter

How to get a normalized staked bar chart using Incanter?


Following this example,

(use '(incanter core stats charts datasets))

(with-data  (get-dataset :airline-passengers)
  (view (stacked-bar-chart :month :passengers :group-by :year :legend true)))

How can I make each global bar equal to 100%, allowing full relative comparisons between stacked elements?

Now I get something like this : http://phloxblog.in/angulard3/images/Nor-Stackbar.jpg

How can I achieve this instead? enter image description here


Solution

  • I found the answer.

    (use '(incanter core stats charts datasets))
    
    (import
       '[org.jfree.chart ChartFactory ChartUtilities JFreeChart StandardChartTheme]
       '[org.jfree.chart.plot CategoryPlot]
       '[org.jfree.chart.renderer.category CategoryItemRenderer StackedBarRenderer])
    
    (with-data  (get-dataset :airline-passengers)
      (view 
       (let [chart (stacked-bar-chart :month :passengers :group-by :year :legend true)
             plot (-> chart .getCategoryPlot)
             renderer (-> plot .getRenderer)
             _ (.setRenderAsPercentages renderer true)] 
         chart)))
    

    Before: enter image description here

    After: enter image description here

    If you want to get axis in percent, you can do

    (use '(incanter core stats charts datasets))
    
    (import
       '[org.jfree.chart ChartFactory ChartUtilities JFreeChart StandardChartTheme]
       '[org.jfree.chart.axis NumberAxis]
       '[org.jfree.chart.labels StandardCategoryItemLabelGenerator ItemLabelPosition ItemLabelAnchor]
       '[org.jfree.chart.plot CategoryPlot]
       '[org.jfree.chart.renderer.category StackedBarRenderer]
       '[java.text DecimalFormat])
    
    (with-data (get-dataset :airline-passengers)
      (view 
       (let [chart (stacked-bar-chart :month :passengers :group-by :year :legend true)
             plot (-> chart .getCategoryPlot)
             range-axis (-> plot .getRangeAxis)
             percent-format (DecimalFormat. "#%") ;;"#.0%"
             _ (.setNumberFormatOverride range-axis percent-format)
             renderer (-> plot .getRenderer) 
             _ (.setRenderAsPercentages renderer true)] 
         chart)))