<p>What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%?</p>

<p>I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much.</p>

<p>Based on Marius and Andy's answers I'm using the following solution:</p>

<pre><code>double red = (percent &lt; 50) ? 255 : 256 - (percent - 50) * 5.12;
double green = (percent &gt; 50) ? 255 : percent * 5.12;
var color = Color.FromArgb(255, (byte)red, (byte)green, 0);
</code></pre>

<p>Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ...</p>

[{'answer_id': 25012, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 1, 'selected': False, 'text': '<p>As yellow is a mix of red and green, you can probably start with <code>#F00</code> and then slide green up until you hit <code>#FF0</code>, then slide red down to <code>#0F0</code>:</p>\n\n<pre><code>for (int i = 0; i &lt; 100; i++) {\n    var red = i &lt; 50\n        ? 255\n        : 255 - (256.0 / 100 * ((i - 50) * 2));\n    var green = i &lt; 50\n        ? 256.0 / 100 * (i * 2)\n        : 255;\n    var col = Color.FromArgb((int) red, (int) green, 0);\n}\n</code></pre>\n'}, {'answer_id': 25014, 'author': 'Cade', 'author_id': 565, 'author_profile': 'https://Stackoverflow.com/users/565', 'pm_score': 3, 'selected': False, 'text': '<p>In pseudocode.  </p>\n\n<ul>\n<li><p>From 0-50% your hex value would be FFxx00 where:</p>\n\n<pre><code>XX = ( Percentage / 50 ) * 255 converted into hex.\n</code></pre></li>\n<li><p>From 50-100 your hex value would be  xxFF00 where:</p>\n\n<pre><code>XX = ((100-Percentage) / 50) * 255 converted into hex.  \n</code></pre></li>\n</ul>\n\n<p>Hope that helps and is understandable.</p>\n'}, {'answer_id': 25017, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': -1, 'selected': False, 'text': "<p>Because it's R-G-B, the colors go from integer values of -1 (white), to -16777216 for black.  with red green and yellow somewhere in the middle that.  Yellow is actually -256, while red is -65536 and green is -16744448.  So yellow actually isn't between red and green in the RGB notation.  I know that in terms of wavelenghts, green is on one side, and red is on the other side of the spectrum, but I've never seen this type of notation used in computers, as the spectrum doesn't represent all visible colours.</p>\n"}, {'answer_id': 25024, 'author': 'Marius', 'author_id': 1585, 'author_profile': 'https://Stackoverflow.com/users/1585', 'pm_score': 5, 'selected': True, 'text': '<p>I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language:</p>\n\n<pre><code>function setColor(p){\n    var red = p&lt;50 ? 255 : Math.round(256 - (p-50)*5.12);\n    var green = p&gt;50 ? 255 : Math.round((p)*5.12);\n    return "rgb(" + red + "," + green + ",0)";\n}\n</code></pre>\n'}, {'answer_id': 25065, 'author': 'Henrik Gustafsson', 'author_id': 2010, 'author_profile': 'https://Stackoverflow.com/users/2010', 'pm_score': 3, 'selected': False, 'text': '<p>What you probably want to do is to assign your 0% to 100% some points in a HSV or HSL color-space. From there you can interpolate colors (and yellow just happens to be between red and green :) and <a href="http://en.wikipedia.org/wiki/HSL_color_space" rel="nofollow noreferrer">convert them to RGB</a>. That will give you a nice looking gradient between the two.</p>\n<p>Assuming that you will use the color as a status indicator and from a user-interface perspective, however, that is probably not such a good idea, since we\'re quite bad at seeing small changes in color. So dividing the value into, for example, three to seven buckets would give you more noticeable differences when things change, at the cost of some precision (which you most likely would not be able to appreciate anyway).</p>\n<p>So, all the math aside, in the end I\'d recommend a lookup table with the following colors with v being the input value:</p>\n<pre><code>#e7241d for v &lt;= 12%\n#ef832c for v &gt; 12% and v &lt;= 36%\n#fffd46 for v &gt; 36% and v &lt;= 60%\n#9cfa40 for v &gt; 60% and v &lt;= 84%\n#60f83d for v &gt; 84%\n</code></pre>\n<p>These have been very naïvely converted from HSL values (0.0, 1.0, 1.0), (30.0, 1.0, 1.0), (60.0, 1.0, 1.0), (90.0, 1.0, 1.0), (120.0, 1.0, 1.0), and you might want to adjust the colors somewhat to suit your purposes (some don\'t like that red and green aren\'t \'pure\').</p>\n<p>Please see:</p>\n<ul>\n<li><a href="http://richnewman.wordpress.com/2007/04/29/using-hsl-color-hue-saturation-luminosity-to-create-better-looking-guis-part-1/" rel="nofollow noreferrer">Using HSL Color (Hue, Saturation, Luminosity) To Create Better-Looking GUIs</a> for some discussion and</li>\n<li><a href="https://web.archive.org/web/20141023005253/http://bobpowell.net/RGBHSB.aspx" rel="nofollow noreferrer">RGB and HSL Colour Space Conversions</a> for sample C# source-code.</li>\n</ul>\n'}, {'answer_id': 43215, 'author': 'Tom', 'author_id': 3715, 'author_profile': 'https://Stackoverflow.com/users/3715', 'pm_score': 0, 'selected': False, 'text': '<p>I use the following Python routines to blend between colours:</p>\n\n<pre><code>def blendRGBHex(hex1, hex2, fraction):\n    return RGBDecToHex(blendRGB(RGBHexToDec(hex1), \n                                RGBHexToDec(hex2), fraction))\n\ndef blendRGB(dec1, dec2, fraction):\n    return [int(v1 + (v2-v1)*fraction) \n        for (v1, v2) in zip(dec1, dec2)]\n\ndef RGBHexToDec(hex):\n    return [int(hex[n:n+2],16) for n in range(0,len(hex),2)]\n\ndef RGBDecToHex(dec):\n    return "".join(["%02x"%d for d in dec])\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>&gt;&gt;&gt; blendRGBHex("FF8080", "80FF80", 0.5)\n"BFBF80"\n</code></pre>\n\n<p>Another routine wraps this to blend nicely between numerical values for "conditional formatting":</p>\n\n<pre><code>def colourRange(minV, minC, avgV, avgC, maxV, maxC, v):\n    if v &lt; minV: return minC\n    if v &gt; maxV: return maxC\n    if v &lt; avgV:\n        return blendRGBHex(minC, avgC, (v - minV)/(avgV-minV))\n    elif v &gt; avgV:\n        return blendRGBHex(avgC, maxC, (v - avgV)/(maxV-avgV))\n    else:\n        return avgC\n</code></pre>\n\n<p>So, in Jonas\' case:</p>\n\n<pre><code>&gt;&gt;&gt; colourRange(0, "FF0000", 50, "FFFF00", 100, "00FF00", 25)\n"FF7F00"\n</code></pre>\n'}, {'answer_id': 685216, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>I wrote this python function based on the javascript code. it takes a percentage as a decimal. also i have squared the value to keep the colours redder for longer down the percentage scale. I also narrowed the range of colours from 255 to 180 to give a darker red and green at each end. these can be played with to give nice colours. I\'d like to add a touch of orange in the middle, but i gotta get on with proper work, boo.</p>\n\n<pre><code>def getBarColour(value):\n    red = int( (1 - (value*value) ) * 180 )\n    green = int( (value * value )* 180 )\n\n    red = "%02X" % red\n    green = "%02X" % green\n\n    return \'#\' + red + green +\'00\'\n</code></pre>\n'}, {'answer_id': 3660287, 'author': 'Simon', 'author_id': 212903, 'author_profile': 'https://Stackoverflow.com/users/212903', 'pm_score': 0, 'selected': False, 'text': '<p>My solution for ActionScript 3:</p>\n\n<pre><code>var red:Number = (percentage &lt;= 50) ? 255 : 256 - (percentage - 50) * 5.12;\nvar green:Number = (percentage &gt;= 50) ? 255 : percentage * 5.12;\n\nvar redHex:Number = Math.round(red) * 0x10000;\nvar greenHex:Number = Math.round(green) * 0x100;\n\nvar colorToReturn:uint = redHex + greenHex;\n</code></pre>\n'}, {'answer_id': 27901262, 'author': 'Mark Whitaker', 'author_id': 440921, 'author_profile': 'https://Stackoverflow.com/users/440921', 'pm_score': 2, 'selected': False, 'text': "<p>This is a nice clean solution that improves on the currently accepted answer in three ways:</p>\n\n<ol>\n<li>Removes the magic number (5.12), therefore making the code easier to follow.</li>\n<li>Won't produce the rounding error that's giving you -1 when the percentage is 100%.</li>\n<li>Allows you to customise the minimum and maximum RGB values you use, so you can produce a lighter or darker range than simple rgb(255, 0, 0) - rgb(0, 255, 0).</li>\n</ol>\n\n<p>The code shown is C# but it's trivial to adapt the algorithm to any other language.</p>\n\n<pre><code>private const int RGB_MAX = 255; // Reduce this for a darker range\nprivate const int RGB_MIN = 0; // Increase this for a lighter range\n\nprivate Color getColorFromPercentage(int percentage)\n{\n    // Work out the percentage of red and green to use (i.e. a percentage\n    // of the range from RGB_MIN to RGB_MAX)\n    var redPercent = Math.Min(200 - (percentage * 2), 100) / 100f;\n    var greenPercent = Math.Min(percentage * 2, 100) / 100f;\n\n    // Now convert those percentages to actual RGB values in the range\n    // RGB_MIN - RGB_MAX\n    var red = RGB_MIN + ((RGB_MAX - RGB_MIN) * redPercent);\n    var green = RGB_MIN + ((RGB_MAX - RGB_MIN) * greenPercent);\n\n    return Color.FromArgb(red, green, RGB_MIN);\n}\n</code></pre>\n\n<h3>Notes</h3>\n\n<p>Here's a simple table showing some percentage values, and the corresponding red and green proportions we want to produce:</p>\n\n<pre><code>VALUE   GREEN    RED       RESULTING COLOUR\n 100%    100%     0%       green\n  75%    100%    50%       yellowy green\n  50%    100%   100%       yellow\n  25%     50%   100%       orange\n   0%      0%   100%       red\n</code></pre>\n\n<p>Hopefully you can see pretty clearly that</p>\n\n<ul>\n<li>the green value is 2x the percentage value (but capped at 100)</li>\n<li>the red is the inverse: 2x (100 - percentage) (but capped at 100)</li>\n</ul>\n\n<p>So my algorithm calculates the values from a table looking something like this...</p>\n\n<pre><code>VALUE   GREEN    RED\n 100%    200%     0%\n  75%    150%    50%\n  50%    100%   100%\n  25%     50%   150%\n   0%      0%   200%\n</code></pre>\n\n<p>...and then uses <code>Math.Min()</code> to cap them to 100%.</p>\n"}]
['https://Stackoverflow.com/questions/25007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1199387/']