1

So, I am using the answer to this question to color some values I have for some polygons to plot to a basemap instance. I modified the function found in that link to be the following. The issue I'm having is that I have to convert the string that it returns to a hex digit to use so that I can color the polygons. But when I convert something like "0x00ffaa" to a python hex digit, it changes it to be "0xffaa", which cannot be used to color the polygon

How can I get around this?

Here is the modified function:

def rgb(mini,maxi,value):
    mini, maxi, value = float(mini), float(maxi), float(value)
    ratio = 2* (value - mini) / (maxi-mini)
    b = int(max(0,255*(1-ratio)))
    r = int(max(0,255*(ratio -1)))
    g = 255 - b - r
    b = hex(b)
    r = hex(r)
    g = hex(g)
    if len(b) == 3:
        b = b[0:2] + '0' + b[-1]
    if len(r) == 3:
        r = r[0:2] + '0' + r[-1]
    if len(g) == 3:
        g = g[0:2] + '0' + g[-1]
    string = r+g[2:]+b[2:]
    return string
Community
  • 1
  • 1
K. Shores
  • 875
  • 1
  • 18
  • 46
  • So, just to make this clear for other people like me who have flawed understandings, rgb values must be passed in the form '#00ffaa', notice the pound symbol. See http://matplotlib.org/api/colors_api.html . – K. Shores Oct 12 '15 at 19:46

2 Answers2

1

Use string formatting, for example:

>>> "0x%08x" % 0xffaa
'0x0000ffaa'
cdarke
  • 42,728
  • 8
  • 80
  • 84
1

The answer from cdarke is OK, but using the % operator for string interpolation is kind of deprecated. For the sake of completion, here is the format function or the str.format method:

>>> format(254, '06X')
'0000FE'

>>> "#{:06X}".format(255)
'#0000FF'

New code is expected to use one of the above instead of the % operator. If you are curious about "why does Python have a format function as well as a format method?", see my answer to this question.

But usually you don't have to worry about the representation of the value if the function/method you are using takes integers as well as strings, because in this case the string '0x0000AA' is the same as the integer value 0xAA or 170.

Community
  • 1
  • 1
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
  • This helps, yet I'm not sure that I understand how to use it. What I am using right now is color_string.format(255), which will give me something like "0x00ffaa" (for whatever input that needs to be). But I need to pass the color as a hex digit, so then I use hex(int(color_string,16)) which then puts the number back to "0xffaa", which cannot be used as an rgb color value. Does that help explain my confusion? – K. Shores Oct 12 '15 at 19:39
  • Except the real format that is expected is '#000000', isn't it? Yay, flaws in understanding! – K. Shores Oct 12 '15 at 19:44