@@ -833,3 +833,48 @@ def get_colorscale(name):
833
833
if should_reverse :
834
834
return colorscale [::- 1 ]
835
835
return colorscale
836
+
837
+
838
+ def sample_colorscale (colorscale , samplepoints , low = 0.0 , high = 1.0 , colortype = "rgb" ):
839
+ """
840
+ Samples a colorscale at specific points.
841
+
842
+ Interpolates between colors in a colorscale to find the specific colors
843
+ corresponding to the specified sample values. The colorscale can be specified
844
+ as a list of `[scale, color]` pairs, as a list of colors, or as a named
845
+ plotly colorscale. The samplepoints can be specefied as an iterable of specific
846
+ points in the range [0.0, 1.0], or as an integer number of points which will
847
+ be spaced equally between the low value (default 0.0) and the high value
848
+ (default 1.0). The output is a list of colors, formatted according to the
849
+ specified colortype.
850
+ """
851
+ from bisect import bisect_left
852
+
853
+ try :
854
+ validate_colorscale (colorscale )
855
+ except exceptions .PlotlyError :
856
+ if isinstance (colorscale , str ):
857
+ colorscale = get_colorscale (colorscale )
858
+ else :
859
+ colorscale = make_colorscale (colorscale )
860
+
861
+ scale = colorscale_to_scale (colorscale )
862
+ validate_scale_values (scale )
863
+ colors = colorscale_to_colors (colorscale )
864
+ colors = validate_colors (colors , colortype = "tuple" )
865
+
866
+ if isinstance (samplepoints , int ):
867
+ samplepoints = [
868
+ low + idx / (samplepoints - 1 ) * (high - low ) for idx in range (samplepoints )
869
+ ]
870
+ elif isinstance (samplepoints , float ):
871
+ samplepoints = [samplepoints ]
872
+
873
+ sampled_colors = []
874
+ for point in samplepoints :
875
+ high = bisect_left (scale , point )
876
+ low = high - 1
877
+ interpolant = (point - scale [low ]) / (scale [high ] - scale [low ])
878
+ sampled_color = find_intermediate_color (colors [low ], colors [high ], interpolant )
879
+ sampled_colors .append (sampled_color )
880
+ return validate_colors (sampled_colors , colortype = colortype )
0 commit comments