01/02/2023

How to get a matplotlib colormap into inkscape.

Inelegant, but works.

TL;DR: let python create an SVG file with a rectangle that uses the colormap as a gradient. Open, import or copy in inkscape.

Python code (this one gives coolwarm012.svg in your working directory):

ncol=12 #number of stops
grad='coolwarm' #name of matplotlib gradient
from matplotlib import colors, cm
import numpy as np

stopstr="""  <stop
    style="stop-color:%s;stop-opacity:1"
    offset="%.4f"
    id="stop%03d" />"""

init="""<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   width="1cm"
   height="1cm"
   viewBox="0 0 1 1"
   id="svg">   
  <defs id="defs">
    <linearGradient
       id="%s%03d">
"""%(grad,ncol)

exit="""
</linearGradient>
</defs>
<rect
       style="fill:url(#%s%03d)"
       id="rectangle"
       width="1"
       height="1"
       x="0"
       y="0"/>
</svg>"""%(grad,ncol)

cmap = cm.get_cmap(grad, ncol)   
spac=np.linspace(0,1,ncol)

#saves  <gradientname+numberofstops>.svg with a 1x1cm^2 rectangle using the gradient 
with open('%s%03d.svg'%(grad,ncol),'w') as f:
    f.write(init)
    for i in range(cmap.N):
        rgba = cmap(i)
        hexcol = colors.rgb2hex(rgba)
        f.write(stopstr%(hexcol,spac[i],i))
    f.write(exit)

Some code taken from https://stackoverflow.com/questions/33596491/extract-matplotlib-colormap-in-hex-format

No comments: