Charting s/w: do you really need one?

how-to
Oct 8, 20082 mins

Had to draw a pie chart few days back. Took a look at some charting software stack. The effort to learn them I couldn’t bear, And decided to create a small AWT ware. The prose of life is: to draw a simple pie chart sometimes it is easier to write your own AWT piece of code than to learn and install some third-party s/w. Prepare 100×100 anti-aliased drawing pane:


BufferedImage buffer = new BufferedImage(100,100,BufferedImage.TYPE_INT_RGB); // ARGB for alpha channel (transparency)
Graphics2D g = buffer.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.white);
g.fillRect(0,0,100,100);

Iterate through values (suppose we have Name-Value map), use high-school math to calculate label position:


int arc = 0;
Map mpNamePnt = new HashMap();
for(String name : nameValue.keySet()) {
color = new Color((int) (Math.random() * 200 + 55), (int) (Math.random() * 200 + 55), (int) (Math.random() * 200 + 55));
g.setColor(color);
double dDegrees = 360f / 100f * nameValue.get(name);
g.fillArc(0,0,100,100,arc, (int)dDegrees);
int iX = (int) (35 + (20 * Math.cos(Math.toRadians(arc + (dDegrees / 2)))));
int iY = (int) (50 - (20 * Math.sin(Math.toRadians(arc + (dDegrees / 2)))));
mpNamePnt.put(name, new Point(iX, iY));
arc += dDegrees;
}

Iterate through labels and render them:


for (Iterator itPnt = mpNamePnt.keySet().iterator(); itPnt.hasNext();) {
String sName = (String)itPnt.next();
Point p = (Point)mpNamePnt.get(sName);
g.setFont(font);
g.setColor(Color.black);
g.drawString(sName, p.x, p.y);
}

Now write image to an output stream:


ImageIO.write(buffer, "png", outputStream);