Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bubble plot in python (saves to SVG)
"""
Read in CSV of label, value
Need two commandline arguments: csv and svg files. e.g.
python bubblify.py 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" />
"""
import sys
import math
import operator
fh = open(sys.argv[1],"r"); #CSV input
fout = open(sys.argv[2],"w"); #SVG output
fout.write("""<?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">
""")
#Initialize variables
data={}
headers=None
#Read in the data
for line in fh:
if headers==None:
#First line is labels
headers=line
else:
vals=line.split(",")
data[vals[0].strip()]=float(vals[1].strip())
#Draw the circles
x=0
y=0
min_val=min(data.iteritems(), key=operator.itemgetter(1))[1]
max_val=max(data.iteritems(), key=operator.itemgetter(1))[1]
for key in data:
val=data[key]
s="<rect id=\"{}\"".format(key)
area=(val-min_val)/(max_val-min_val)*5000 #Largest now to have area of 500
r = math.sqrt(area/math.pi)
d=r*2 #Now diameter
x=x+d
if x>1000: #Move to next row
x=0;
y=y+r;
s+=" width=\"{d}\" height=\"{d}\" rx=\"{r}\" ry=\"{r}\" x=\"{x}\" y=\"{y}\"/>\n".format(d=d,r=r,x=x,y=y)
fout.write(s)
fout.write("</g>\n")
fout.write("</svg>\n")
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.