Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP code to make a bubble plot SVG file
<?php
/*
Read in CSV of label, value
Need two commandline arguments: csv and svg files. e.g.,
php bubblify.php somefile.csv output.svg
Write SVG for circles of each value
Circle area varies with value from csv
Future:
No text labels currently
<rect
style="fill:#0000ff;fill-opacity:1;stroke:#9df3b1;stroke-width:0.28428069;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0"
id="rect3036"
width="50"
height="50"
x="73.827858"
y="709.10571"
rx="25"
ry="25" />
*/
//Test for two
$fh = fopen($argv[1],"r"); //CSV input file
$fout = fopen($argv[2],"w"); //SVG output file
fwrite($fout,file_get_contents("svg_header.txt"));
$arrVals=array();
//First line is labels
$line=fgetcsv($fh);
//Second line, initialize array
$valIndex=1;
$nameIndex=0;
$line=fgetcsv($fh);
$val=trim($line[$valIndex]);
$arrVals[$line[$nameIndex]]=$val;
$max=$val;
$min=$val;
while(false!==($line=fgetcsv($fh))) {
$val=trim($line[$valIndex]);
$arrVals[$line[$nameIndex]]=$val;
if ($val>$max) $max=$val;
elseif ($val<$min) $min=$val;
}
asort($arrVals);
$x=0;
$y=0;
foreach ($arrVals as $key=>$val) {
$s="<rect id=\"$key\"";
$area=($val-$min)/($max-$min)*500;//Largest now to have area of 500
$r = sqrt($area/pi());
$d=$r*2;//Now diameter
$x=$x+$d;
if ($x>1000) {
$x=0;
$y=$y+$r;
}
//a=3.14*r^2
$s.=" width=\"$d\" height=\"$d\" rx=\"$r\" ry=\"$r\" x=\"$x\" y=\"$y\"/>\n";
fwrite($fout,$s);
}
fwrite($fout,"</g>\n");
fwrite($fout,"</svg>\n");
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
version="1.1"
width="744.09448"
height="1052.3622"
id="svg2">
<defs
id="defs4" />
<metadata
id="metadata7">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
id="layer1">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.