Setting vertical axis origin to non-zero

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

Setting vertical axis origin to non-zero

Post by Angela » Tue Jun 12, 2001 1:51 pm

Hi all,

I am trying to graphically display daily hits on a portion of a web site. Since there are already a number of hits I wish to allow the vertical axis to start from some non-zero number.

The code fragment below appears to have no effect

Plot plot = chart.getPlot();
((VerticalNumberAxis)plot.getVerticalAxis()).setAutoRangeIncludesZero(false);

Errant graphs are here http://www.shoppingclassifieds.co.uk/au ... tStats.jsp

Anyone able to offer any insight, please?


Angela

David Gilbert

RE: Setting vertical axis origin to non-zero

Post by David Gilbert » Tue Jun 12, 2001 9:41 pm

Hi Angela,

It's a little hard to say what is going wrong without seeing more of your code. Do you have the autoRange property (in ValueAxis) set to true? It's the default, but you don't appear to have any margin above the maximum point on your plot, which I would expect to see if autoRange=true.

Aside from that, have you implemented the XYDataSource in your own class? There could be a problem there...post or e-mail some more details and I'll do my best to work out the problem.

It's great to see JFreeChart (almost) working live on the internet!!

Regards,

DG.

Angela

RE: Setting vertical axis origin to non-zero

Post by Angela » Wed Jun 13, 2001 3:23 pm

Hi David,

I have enclosed most of the code that creates the chart. A brief rundown follows: I have implemented the XYDataSource interface with my own class, ImpXYDataSource, that expects an array of Points as its data source. I needed to have data saved to disc so a wrapper class PointVector was written that could be serialized in and out. As daily point data is added to the PointVector array of Points, the instance is resaved to disc including the new Point.

symbiantHits.jsp is the orchestrating code that:-
interrogates the database,
loads the previously serialized PointVector,
decides if a new point needs to be added.
creates a jpeg from com.jrefinery.chart and saves it to disc.
Also symbiantHits tries to stop zero appearing in the Y axis range

No changes to ValueAxis are made - just relying on the default.

Code follows.

Others whom may be following this, please feel free to build on my attemps to get to grips with the com.jrefinery.chart API

Angela

***************************** class ImpXYDataSource starts **********************************************************************
/*
* ImpXYDataSource.java
*
* Created on 24 May 2001, 10:09
*/
package audit;



import com.jrefinery.chart.*;
import java.util.*;
import java.awt.Point;

/**
*
* @author angelac
* @version
*/
public class ImpXYDataSource extends com.jrefinery.chart.AbstractDataSource implements XYDataSource {

private int XData = 0;
private int YData = 0;
private int seriesCount = 0;
protected String seriesName = null;
protected Point[] points;
protected List seriesNames;


/** Creates new ImpXYDataSource */
public ImpXYDataSource() {
}
public ImpXYDataSource(Point[] p){
this.points=p;
}
public ImpXYDataSource(java.util.List seriesNames,Point[] p){
this.points=p;
this.seriesNames=seriesNames;
}

public int getSeriesCount() {
return 1;
}

public java.lang.String getSeriesName(int seriesIndex) {
return "Live Data";
}

public int getItemCount(int seriesIndex) {
return points.length;
}
public Number getXValue(int seriesIndex,int itemIndex) {
return new Double(points[itemIndex].getX());
}
public Number getYValue(int seriesIndex, int itemIndex) {
return new Double(points[itemIndex].getY());
}
}
***************************** class ImpXYDataSource ends **********************************************************************

***************************** class PointVector starts **********************************************************************

/*
* PointVector.java
*
* Created on 29 May 2001, 16:45
*/
package audit;

import java.beans.*;
import java.awt.*;
import java.io.*;
import java.util.Date;

/**
*
* @author angelac
* @version
*/

public class PointVector extends Object implements java.io.Serializable {
static final long serialVERSIONUID= 28043293785475531L;
private static final String PROP_DATE_PROPERTY ="11-Jun-01";
private static final String PROP_CURRHITS_PROPERTY = "0";
private static final String PROP_SYMBIANTHITS_PROPERTY = "0";
private String dateProperty;
private String hitsProperty;
private String symbiantHitsProperty;
private PropertyChangeSupport propertySupport;
private Point[] points= new Point[0];
private transient int size=0;

/** Creates new PointVector */
public PointVector() {
propertySupport = new PropertyChangeSupport ( this );
}

public PointVector(int x, int y) {
propertySupport = new PropertyChangeSupport ( this );
this.add(new Point(x,y));
}
/* return element from array */
public Point elementAt(int index)throws ArrayIndexOutOfBoundsException{
if (index>=size) throw new ArrayIndexOutOfBoundsException(index);
else return points[index];
}
/** add point to array and grow if required */
public void add(Point p){
if(points.length==size) resize(points.length+1);
points[size++]=p;
}
/** resize array routine */
protected void resize(int newsize){
Point[] oldPoints = points;
points=new Point[newsize];
System.arraycopy(oldPoints,0,points,0, size);
}

/** compute transient size after deserializing the array */
private void readObject(ObjectInputStream in) throws IOException ,ClassNotFoundException{
in.defaultReadObject();
size=points.length;
}
/** provide point array */
public Point[] getPoints(){
return points;

}
public int getSize(){
return size;
}

public String getDateProperty () {
return dateProperty;
}

public void setDateProperty (String value) {
String oldValue = dateProperty;
dateProperty = value;
propertySupport.firePropertyChange (PROP_DATE_PROPERTY, oldValue, dateProperty);
}
public String getCurrentHitProperty () {
return hitsProperty;
}

public void setCurrentHitProperty (String value) {
String oldValue = dateProperty;
hitsProperty = value;
propertySupport.firePropertyChange (PROP_CURRHITS_PROPERTY, oldValue, dateProperty);
}
public String getSymbiantHitProperty () {
return symbiantHitsProperty;
}

public void setSymbiantHitProperty (String value) {
String oldValue = symbiantHitsProperty;
symbiantHitsProperty = value;
propertySupport.firePropertyChange (PROP_SYMBIANTHITS_PROPERTY, oldValue, symbiantHitsProperty);
}

public void addPropertyChangeListener (PropertyChangeListener listener) {
propertySupport.addPropertyChangeListener (listener);
}

public void removePropertyChangeListener (PropertyChangeListener listener) {
propertySupport.removePropertyChangeListener (listener);
}


}
***************************** class PointVector ends **********************************************************************

*****************************JSP Page symbiantHits.jsp follows **********************************************************************

<%@page import="java.sql.*, java.io.*,java.util.zip.*,java.awt.*"%>
<%@ page import="javax.servlet.*,javax.servlet.http.*, com.jrefinery.chart.*,com.sun.image.codec.jpeg.*,java.util.*,audit.*" %>


<%!

/* this jsp page checks the need to update a graph with
another Point and writes the serialized PointVector instance (Array of Points)
to file. In image of the graph is created from the updated
PointVector instance and also written to file.

This code is called as an included file from symbiantStats.jsp
*/
ObjectInputStream objIn2=null;
Point[] oldPoints2= null;
PointVector pointVector2=null;
int size2=0;
int type2 = 1;
int initGradColor2= 0;
int finalGradColor2= 6;
%>

<%
/** read instance of PointVector in */
try{
FileInputStream filein2=new FileInputStream("serialized/PointVectorObject2");
GZIPInputStream gzip2=new GZIPInputStream(filein2);
objIn2= new ObjectInputStream(gzip2);
}catch(Exception e){out.println(e);}
/* if instance exists */
if (objIn2 != null){
/** load old graph points */
pointVector2 = (PointVector)objIn2.readObject();
size2=pointVector2.getSize();
objIn2.close();
}else /* no instance create new */
pointVector2=new PointVector(0,150); // (0,150) graph start value .. clunky needs refining
/** Get new point from database*/
Driver DriverRecordset4 = (Driver)Class.forName(MM_Squawkbox_DRIVER).newInstance();
Connection ConnRecordset4 = DriverManager.getConnection(MM_Squawkbox_STRING,MM_Squawkbox_USERNAME,MM_Squawkbox_PASSWORD);
PreparedStatement StatementRecordset4 = ConnRecordset4.prepareStatement("SELECT SUM(totalHits) FROM SCsymbiant");
ResultSet Recordset4 = StatementRecordset4.executeQuery();
int newY2=0;
if(Recordset4.next()) newY2=Recordset4.getInt(1);

/** add databse derived point to existing data */
// *********** comment out for 'test' or 'runtime' **************
// runtime plots one point daily **************************************************
//if (objIn2==null) pointVector2.setDateProperty((new java.util.Date(System.currentTimeMillis()).toLocaleString()).substring(0,9));
//if (pointVector2.getDateProperty().equals((new java.util.Date(System.currentTimeMillis()).toLocaleString()).substring(0,9)))
// test plots new point each refresh **********************************************
if (objIn2==null) pointVector2.setDateProperty(new java.util.Date(System.currentTimeMillis()).toLocaleString());
if (pointVector2.getDateProperty().equals((new java.util.Date(System.currentTimeMillis()).toLocaleString())))
;// do nothing
else {
// reset date property in PointVector
// comment out for test or runtime
// runtime *************************************************
//pointVector2.setDateProperty((new java.util.Date(System.currentTimeMillis()).toLocaleString()).substring(0,9));
// test ****************************************************
pointVector2.setDateProperty((new java.util.Date(System.currentTimeMillis()).toLocaleString())); // this
//* write point data to pointVector */
size2=pointVector2.getSize();
Point newPoint2= new Point(size2,newY2);
pointVector2.add(newPoint2);
}
/** serialize pointVector */
try{
FileOutputStream fos2= new FileOutputStream("serialized/PointVectorObject2");
GZIPOutputStream gzip2= new GZIPOutputStream(fos2);
ObjectOutputStream objOut2=new ObjectOutputStream(gzip2);
objOut2.writeObject(pointVector2);
objOut2.flush();
objOut2.close();
}catch(Exception e){out.println(e);}
%>
<% Point[] myPoints2=pointVector2.getPoints();
ImpXYDataSource data2 = new ImpXYDataSource(myPoints2);
com.jrefinery.chart.JFreeChart chart2 = com.jrefinery.chart.JFreeChart.createXYChart(data2);
%>
<%
chart2.setChartBackgroundPaint(new GradientPaint(0, 0, getColor2( initGradColor2 ), 1000, 0, getColor2( finalGradColor2 )));
chart2.setTitle("Total Hits to Symbiants from Shopping Classifieds");
Plot plot2=chart2.getPlot();
Axis haxis2=(Axis)plot2.getHorizontalAxis();
haxis2.setLabel("days since 11/06/01");
Axis vaxis2=(Axis)plot2.getVerticalAxis();
vaxis2.setLabel("total hits");
((VerticalNumberAxis) plot2.getVerticalAxis()).setAutoRangeIncludesZero(false);
int width2 = 800;
int height2 = 600;
BufferedImage img2 = draw2( chart2, width2, height2 );
JPEGImageEncoder encoder2 =
JPEGCodec.createJPEGEncoder( new FileOutputStream("../webapps/pfi/audit/image/graph2.jpg")); // draws to file
JPEGEncodeParam param2 =
encoder2.getDefaultJPEGEncodeParam(img2);
param2.setQuality(0.8f,true); // 80% quality
encoder2.encode(img2,param2);
%>

<%!
public Color getColor2(int color)
{
switch (color % 11) {
case 0: return new Color(204,153,255);
case 1: return Color.black;
case 2: return Color.blue;
case 3: return Color.green;
case 4: return Color.red;
case 5: return Color.yellow;
case 6: return new Color(204,204,255);
case 7 : return Color.orange;
case 8: return Color.cyan;
case 9: return Color.magenta;
case 10: return Color.pink;
default: return Color.white;
}

}

public BufferedImage draw2(JFreeChart chart, int width, int height)
{
BufferedImage img =
new BufferedImage(width , height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = img.createGraphics();
chart.draw(g2, new Rectangle2D.Double(0, 0, width, height));
g2.dispose();
return img;
}
%>

<%
Recordset4.close();
ConnRecordset4.close();
%>
********************** all code ends ***********************

Angela

RE: Setting vertical axis origin to non-zero

Post by Angela » Thu Jun 14, 2001 10:51 am

Hi All,

may I answer my own question? Seems the solution is to call

((VerticalNumberAxis) plot.getVerticalAxis()).autoAdjustRange();

after setting the boolean autoRangeIncludesZero to false with

((VerticalNumberAxis) plot.getVerticalAxis()).setAutoRangeIncludesZero(false);

There you go!


Angela

Locked