# Programming multiple colors with Color Ramp in PythonAPI

Hi I am struggling to get rid of InfroError caused by ColorRamp. Is there any concise way to represent the colorRamp shown below?

My messy code

The Error Message

import bpy

bl_space_type = "VIEW_3D"
bl_region_type = "UI"
def draw(self,context):
layout = self.layout
row = layout.row()

bl_label = "RUBY"

def execute(self,context):

activeObject = bpy.context.active_object

mat_ruby = bpy.data.materials.new(name="Ruby")

mat_ruby.use_nodes = True

activeObject.data.materials.append(mat_ruby)

mat_ruby.node_tree.nodes.remove(mat_ruby.node_tree.nodes.get('Principled BSDF'))

# material output
mat_output = mat_ruby.node_tree.nodes.get("Material Output")

mat_output.location = (-400,0)

glassA.location = (-600,0)
glassA.inputs[1].default_value=0.141

glassB.location = (-600,200)
glassB.inputs[0].default_value=(0.396755,0.177888,0.201556,1)
glassB.inputs[1].default_value=0.141

#colorRamp
ramp.location = (-800,100)
for r in ramp:

ramp.color_ramp.elements[0].color = (0.215861,0,0.017642,1)
ramp.color_ramp.elements[0].position = 0.102
ramp.color_ramp.elements[1].color = (0.396755,0,0.032,1)
ramp.color_ramp.elements[1].position = 0.636
ramp.color_ramp.elements[2].color = (0.701102,0.147,0.016,1)
ramp.color_ramp.elements[2].position = 0.794
ramp.color_ramp.elements[3].color = (1.0,0.292,0.0,1)
ramp.color_ramp.elements[3].position = 0.893
ramp.color_ramp.elements[4].color = (1.0,1.0,1.0,1)
ramp.color_ramp.elements[4].position = 1

#Vector Math ('DOT_PRODUCT')
math.location = (-1000,100)
math.operation = 'DOT_PRODUCT'

#Geometry
geo.location = (-1200,100)

return {'FINISHED'}

def register():

def unregister():

if __name__ == "__main__":
register()


• Please post code as text, not image. See blender.stackexchange.com/questions/189712/… Dec 13, 2020 at 4:40
• Thanks for replying, I've embedded the coding and the link is super helpful for my case Dec 13, 2020 at 4:46

Your problem is that by default the ramp only has two elements, so your code has to first set values for the existing elements, and then create new elements. Assuming you wanted to leave the original leftmost and rightmost handles alone, you need something along the lines of

    ramp = mat_ruby.node_tree.nodes.new("ShaderNodeValToRGB")
ramp.location = (-800,100)

ramp_colors = [(0.215861,0,0.017642,1), (0.396755,0,0.032,1), (0.701102,0.147,0.016,1), (1.0,0.292,0.0,1)]
ramp_positions = [0.102, 0.636, 0.794, 0.893]

elements = ramp.color_ramp.elements
for i in range(len(ramp_colors)):
element = elements.new(ramp_positions[i])
element.color = ramp_colors[i]


If you want to use the existing handles in your code, set them first, because adding a new element changes the indices.