Stacked Bar Chart Labels

After running into this same issue and many hours running through the forums. I think i found a way to do this. though it is not perfect.

if event.propertyName == "data":
	from org.jfree.chart.labels import CategoryToolTipGenerator
	from org.jfree.chart.labels import StandardCategoryItemLabelGenerator
	from org.jfree.chart.labels import ItemLabelPosition
	from org.jfree.chart.labels import ItemLabelAnchor
	from org.jfree.ui import TextAnchor
	from java.awt import Color

	class myLabelGenerator(StandardCategoryItemLabelGenerator):
		def generateLabel(self,dataset,series,category):	
			value = dataset.getValue(series,category) + dataset.getValue(series+1,category) 	
			if value == 0.0:
				return None
			else:
				return str(round(value,1))
				
	class CustomToolTipGenerator(CategoryToolTipGenerator):
		lines = event.source.parent.getComponent('Bar Chart 1').LineName
		lineName = lines.getColumnAsList(0)
		combined = event.source.parent.getComponent('Toggle Button').selected
		def generateToolTip(self,dataset,row,column):
			OPTag = "OP" + dataset.getColumnKey(column)
			if self.combined:
				OPName = self.lineName[column]
			else:
				OPName = OPTag
			
			return "%s = %s %.1f"%(OPName,dataset.getRowKey(row),(dataset.getValue(row,column)))
		
	chart = event.source.getChart()
	renderer = chart.getPlot().getRenderer()
	renderer.setToolTipGenerator(CustomToolTipGenerator())
	renderer.setSeriesItemLabelGenerator(0,myLabelGenerator())
	renderer.setSeriesItemLabelPaint(1, Color(0,0,0,0))
	renderer.setBasePositiveItemLabelPosition(ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.BOTTOM_CENTER))

This bit of code contains a custom label generator that converts the labels from the 1st series to be a total of all values in that category. and also hides the labels for the other series. there is also some code for a custom tool tip but that isn’t needed here. To move the label just change the Anchors and if you want to add a label that is the total while leaving all other labels un changed, simply add a new column to your data property to create a new series. set all data values for that series to 0 then apply the custom label generator to that new series.

1 Like