Reputation: 718
I'm working in a chart that has the following presentation:
¿How do I make the category labels left aligned or justified? Actually they look centered but that is not what I require.
The code that I'm using is the following:
JFreeChart chart = getChart();
CategoryPlot plot = (CategoryPlot) chart.getPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setDrawBarOutline(true);
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setMaximumCategoryLabelLines(5);
CategoryLabelPositions p = domainAxis.getCategoryLabelPositions();
CategoryLabelPosition left = new CategoryLabelPosition(
RectangleAnchor.LEFT, TextBlockAnchor.CENTER_LEFT,
TextAnchor.CENTER_LEFT, 0.0,
CategoryLabelWidthType.RANGE, 0.70f //Assign 70% of space for category labels
);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions
.replaceLeftPosition(p, left));
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
BasicStroke stroke = new BasicStroke(1);
plot.setDomainGridlinePaint(Color.black);
plot.setDomainGridlineStroke(stroke);
plot.setRangeGridlinePaint(Color.black);
plot.setRangeGridlineStroke(stroke);
CategoryDataset cd = plot.getDataset();
setBarColors(renderer, plot, cd);
Thanks.
Upvotes: 3
Views: 4213
Reputation: 401
The category labels are instances of org.jfree.text.TextBlock
, which does have a setLineAlignment(HorizontalAlignment alignment)
method, but I'm not seeing a way to get to them through the CategoryPlot or CategoryAxis APIs (there are a ton of methods and casts, so I can't tell you definitively such a method doesn't exist, just that I haven't found one). Overriding the createLabel
method in CategoryAxis
to set the alignment works, though.
(before your code to get the domain axis):
plot.setDomainAxis(new CategoryAxis() {
@Override
protected TextBlock createLabel(Comparable category, float width, RectangleEdge edge, Graphics2D g2) {
TextBlock label = TextUtilities.createTextBlock(category.toString(), getTickLabelFont(category), getTickLabelPaint(category), width, this.getMaximumCategoryLabelLines(), new G2TextMeasurer(g2));
label.setLineAlignment(HorizontalAlignment.LEFT);
return label;
}
});
You may want to post a request to the JFreeChart Forums or JFreeChart Feature Requests as David Gilbert would be the best person to answer this definitively.
Upvotes: 3