@@ -806,3 +806,54 @@ def named_colorscales():
806806 from _plotly_utils .basevalidators import ColorscaleValidator
807807
808808 return [c for c in ColorscaleValidator ("" , "" ).named_colorscales ]
809+
810+
811+ def sample_colorscale (colorscale , samplepoints , low = 0.0 , high = 1.0 , colortype = "rgb" ):
812+ """
813+ Samples a colorscale at specific points.
814+
815+ Interpolates between colors in a colorscale to find the specific colors
816+ corresponding to the specified sample values. The colorscale can be specified
817+ as a list of `[scale, color]` pairs, as a list of colors, or as a named
818+ plotly colorscale. The samplepoints can be specefies an iterable of specific
819+ points in the range [0.0, 1.0], or as an integer number of points which will
820+ be spaced equally between the low value (default 0.0) and the high value
821+ (default 1.0). The output is a list of colors, formatted according to the
822+ specified colortype.
823+ """
824+ from bisect import bisect_left
825+
826+ try :
827+ validate_colorscale (colorscale )
828+ except exceptions .PlotlyError :
829+ if isinstance (colorscale , str ):
830+ if colorscale in PLOTLY_SCALES :
831+ colorscale = PLOTLY_SCALES [colorscale ]
832+ else :
833+ raise exceptions .PlotlyError (
834+ "If your colors variable is a string, it must be a "
835+ "Plotly scale, an rgb color or a hex color."
836+ )
837+ else :
838+ colorscale = make_colorscale (colorscale )
839+
840+ scale = colorscale_to_scale (colorscale )
841+ validate_scale_values (scale )
842+ colors = colorscale_to_colors (colorscale )
843+ colors = validate_colors (colors , colortype = "tuple" )
844+
845+ if isinstance (samplepoints , int ):
846+ samplepoints = [
847+ low + idx / (samplepoints - 1 ) * (high - low ) for idx in range (samplepoints )
848+ ]
849+ elif isinstance (samplepoints , float ):
850+ samplepoints = [samplepoints ]
851+
852+ sampled_colors = []
853+ for point in samplepoints :
854+ high = bisect_left (scale , point )
855+ low = high - 1
856+ interpolant = (point - scale [low ]) / (scale [high ] - scale [low ])
857+ sampled_color = find_intermediate_color (colors [low ], colors [high ], interpolant )
858+ sampled_colors .append (sampled_color )
859+ return validate_colors (sampled_colors , colortype = colortype )
0 commit comments