简体   繁体   中英

How to create simple distribution chart of random numbers in a range (java or javascript)

In my simple app i often choose a random number within a given range (0..~500000). I need a simple way to visualize the distribution in a browser. So output options are png, html/js, svg, ascii? .

The data is stored in a simple map (guava's AtomicLongMap ) index->count. I don't need any options. I only want to see the rough quality of ditribution. A tool specialized to visualize distribution that could be directly fed with the map (or map serialized to json) would the best option. In json the data would look like this

{
   "0":6
   "1":3
   "2":4
   "3":0
   "4":2
}

(for a range [0..4])

I got first look at jfreechart and google chart for both i have to convert my map to a special data format and i have to provide labels (i don't need any labels). Some years ago i worked with Birt but this is also very complicated/ overkill for my simple requirement.

A simple approach would be to create an image and draw for each column a line with height of each random number. A simple java code would look like this.

final int AmountNumbers = 1000;
final int MaxSize = 500000;

// create Random Numbers
Random rnd = new Random();
ArrayList<Integer> randomNumbers = new ArrayList<>();
for(int i = 0; i < AmountNumbers; i++)
    randomNumbers.add(rnd.nextInt(MaxSize));

// create picture
int width = AmountNumbers, height = 200;    
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig2 = bi.createGraphics();
ig2.setPaint(Color.red);

// draw lines for every number
for(int i = 0; i < AmountNumbers; i++){
    int rndNumber = randomNumbers.get(i);
    ig2.drawLine( i, rndNumber * height / MaxSize, i,  height); 
}

// save as png
ImageIO.write(bi, "PNG", new File("chart.PNG"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM