Changing colour of XYPlot

A discussion forum for JFreeChart (a 2D chart library for the Java platform).
Locked
Samiul

Changing colour of XYPlot

Post by Samiul » Fri Sep 06, 2002 10:18 am

Hi!!
I just managed to provide a much required functionality that was missing from the package and that is displaying parts of an XYPlot in different colours.
For example, suppose I have an XYPlot and based on whether the present Y-axis value is greater than, less than or equal to the current Y-axis value, the line between these two points is to be displayed in different colors. The only way to change the plot color as per JFreeChart API is to use the "setSeriesPaint" method of the plot classes. But, this changes the colour of the entire plot.
However, I managed to achieve this functionality and I wanted to share it with all users so that they don't have to look for it else where when they require it.
The change required is in the "drawItem" method of "StandardXYItemRenderer" in the "com.jrefinery.chart" package.
The new implementation of the method is as:

public void drawItem(Graphics2D g2, Rectangle2D dataArea, ChartRenderingInfo info,
XYPlot plot, ValueAxis horizontalAxis, ValueAxis verticalAxis,
XYDataset data, int series, int item,
CrosshairInfo crosshairInfo)
{
..............................
..............................
..............................

// get the data point...
Number x1 = data.getXValue(series, item);
Number y1 = data.getYValue(series, item);
if (y1!=null)
{
double transX1 = horizontalAxis.translateValueToJava2D(x1.doubleValue(), dataArea);
double transY1 = verticalAxis.translateValueToJava2D(y1.doubleValue(), dataArea);

Paint paint = getPaint(plot, series, item, transX1, transY1);
if (paint != null)
{
g2.setPaint(paint);
}

if (this.plotLines)
{
if (item>0)
{
// get the previous data point...
Number x0 = data.getXValue(series, item-1);
Number y0 = data.getYValue(series, item-1);
if (y0!=null)
{
double transX0 = horizontalAxis.translateValueToJava2D(x0.doubleValue(), dataArea);
double transY0 = verticalAxis.translateValueToJava2D(y0.doubleValue(), dataArea);

//start of code added by Samiul
double y1Double = ((Double)y1).doubleValue();
double y0Double = ((Double)y0).doubleValue();

if (y1Double>y0Double)
{
g2.setPaint(new Color(0,255,0));
}
else if (y1Double<y0Double)
{
g2.setPaint(new Color(255,0,0));
}
else if (y1Double==y0Double)
{
g2.setPaint(new Color(0,0,255));
}
//end of code added by Samiul
.......................
.......................
.......................
}//method drawItem ends

David Gilbert

Re: Changing colour of XYPlot

Post by David Gilbert » Fri Sep 06, 2002 5:33 pm

Hi Samiul,

Thanks for the code. The best approach for what you are doing is to create a subclass of StandardXYItemRenderer (call it MyCustomXYItemRenderer or whatever) and override the drawItem(...) method.

Regards,

DG.

Locked