# How can I fix the position of the first keyframe while scaling all others?

I have this code that scales all keyframes by half.

But the problem is that it also scales the first keyframe and moves it near zero.

I want to mimic the scaling of keyframes in the viewport editor where the first keyframe is fixed and all others scale by a specific number. Is there a way I can achieve that?

import bpy

# get the active object
obj = bpy.context.active_object
# get the animation data and fcurves from the object
# the fcurves are a good way to get direct access to the keyframes
curves = obj.animation_data.action.fcurves

#loop over every fcurve
for c in curves:
# get the keyframes for every fcurve
keyframes = c.keyframe_points
#loop over every keyframe and divide their x coordinate by a scale factor
for kf in keyframes:
#this is the number to scale by,
#if  you want to scale them all down by half then you'd divide by two
scale_factor = 2.0
# co is the keyframe's coordinate attribute
# we only want to scale them on the x-axis (time)
# not on the y (amplitude)
# /= is a shorthand for saying kf.co.x = kf.co.x / 2
kf.co.x /= scale_factor



import bpy

# get the active object
obj = bpy.context.active_object
# get the animation data and fcurves from the object
# the fcurves are a good way to get direct access to the keyframes
curves = obj.animation_data.action.fcurves

# loop over every fcurve
for c in curves:
# get the keyframes for every fcurve
keyframes = c.keyframe_points
# loop over every keyframe starting from the second one
for i in range(1, len(keyframes)):
kf = keyframes[i]
# this is the number to scale by,
# if you want to scale them all down by half then you'd divide by two
scale_factor = 2.0
# co is the keyframe's coordinate attribute
# we only want to scale them on the x-axis (time)
# not on the y (amplitude)
# /= is a shorthand for saying kf.co.x = kf.co.x / scale_factor
kf.co.x /= scale_factor

$$$$
`
• This approach may induce errors if the initial key is not at 0. For instance if initial key is at frame 4 and the next key is at frame 6 ideally your scale should reflect the delta of the initial key to the next key instead of simply dividing its value.
– Ratt
Aug 15, 2023 at 8:17