Re: histograms
In article <06cm94h18o77oij85pc99vs43l2e2sle2o@4ax.com>,
Roedy Green <see_website@mindprod.com.invalid> wrote:
http://mindprod.com/jgloss/histogram.html
Very nice! Reminds me of the Original Human Tetris:
<http://www.youtube.com/watch?v=G0LtUX_6IXY>
I had recently done something similar to display a histogram of particle
velocities:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.Icon;
import javax.swing.JLabel;
/**
* A Histogram of particle velocities.
*
* @author John B. Matthews
*/
public class Histogram extends JLabel implements Icon {
private static final int WIDTH = 100;
private static final int HEIGHT = 80;
private static final int SPAN = 4;
private static final int BINS = WIDTH / SPAN;
private final int[] bins = new int[BINS];
private ArrayList<Particle> atoms;
private double average = 0;
public Histogram(ArrayList<Particle> atoms) {
this.setIcon(this);
this.atoms = atoms;
}
/**
* Draw a histogram of velocities at the specified location.
* This implementation ignores the Component parameter.
*/
public void paintIcon(Component c, Graphics g, int x, int y) {
if (atoms.isEmpty()) return;
Arrays.fill(bins, 0);
double vMax = Double.MIN_VALUE;
double sum = 0;
for (Particle atom : atoms) {
double v = atom.getVNorm();
vMax = Math.max(vMax, v);
sum += v;
}
average = sum / atoms.size();
int binMax = 0;
for (Particle atom : atoms) {
double v = atom.getVNorm();
int binIndex = (int) (v * (BINS - 1) / vMax);
bins[binIndex]++;
binMax = Math.max(binMax, bins[binIndex]);
}
g.setColor(Color.black);
g.fillRect(0, HEIGHT - 1, WIDTH, 1);
g.setColor(Color.blue);
for (int i = 0; i < bins.length; i++) {
int h = (HEIGHT - 4) * bins[i] / binMax;
g.fillRect(x + i * SPAN, y + HEIGHT - h, SPAN, h);
}
}
public int getIconWidth() {
return WIDTH;
}
public int getIconHeight() {
return HEIGHT;
}
public double getAverage() {
return average;
}
}
--
John B. Matthews
trashgod at gmail dot com
home dot woh dot rr dot com slash jbmatthews