npinti
npinti

Reputation: 52185

Draw Custom Lines using JFreeChart's XYLineAndShapeRenderer

I have some logic which I am using to construct a series of clusters. So far, to denote the cluster to which each point on the graph belongs to, I am using a series of colours, where points belonging to the same cluster are of the same colour.

Besides that, I would also like to display the centre of each cluster since this will help me see how my cluster building algorithm performs. To do this at the moment, I am writing some text on the graph through the use of the XPointerAnnotation class. The problem with this is that I think that having text on top of points can lead to a messy plot (considering that it is highly likely that there will be hundreds of points).

I thought of drawing lines going outwards, from the centre point to each of the members of its cluster. The problem I am facing is that I can't quite seem to find the correct method or methods which does that.

I have managed to find the source of XYLineAndShapeRenderer and have tried to use it as a guide, but I still get no custom lines drawn on the plot. I have tried to override the drawPrimaryLine, drawPrimaryLineAsPath and drawSecondaryPass methods, but to no avail.

The code I am using to render the lines is as follows:

int x1 = (int) dataset.getXValue(series, 0);
int y1 = (int) dataset.getYValue(series, 0);

int x2 = (int) dataset.getXValue(series, item);
int y2 = (int) dataset.getYValue(series, item);

g2.drawLine(x1, y1, x2, y2);
System.out.println(String.format("Drawing %d  %d  %d  %d %s", x1, y1, x2, y2, g2.getColor()));

State s = (State) state;
if (item == s.getLastItemIndex()) {
    // draw path
    drawFirstPassShape(g2, pass, series, item, s.seriesPath);
}

The print statement prints the right coordinates and the right colours, so it just seems that the graphics that I am adding is not being rendered. I have tried calling super, both before and after my code is executed but to no avail either.

Any directions would be appreciated. Thanks.

Upvotes: 2

Views: 1155

Answers (1)

trashgod
trashgod

Reputation: 205785

Looking more closely at the code posted, the xy value obtained from the dataset represents a point in data coordinates. Before such a point can be rendered, it must be transformed into graphics coordinates, relative to the dataArea. As an example, drawPrimaryLineAsPath() uses the corresponding axis method, valueToJava2D(), to convert a data value to a graphics coordinate.

double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);

Addendum: The drawPrimaryLineAsPath() method is invoked from drawItem() only when drawSeriesLineAsPath is true, e.g. setDrawSeriesLineAsPath(true).

Upvotes: 2

Related Questions