Python:为字典中的数值制作颜色刻度
Got it, let's figure out how to make a color scale from your value-to-RGB dictionary. I'll walk you through a practical approach using Python (the go-to tool for this kind of visualization), with options for discrete, continuous, and even web-friendly color scales.
Step 1: Prep your data first
First, we need to sort your dictionary by the numerical values—color scales make the most sense when ordered from lowest to highest. We'll also convert those rgb() strings into a format that visualization libraries can work with.
# Your original color-value dictionary colormap_coms = { 0.10208554259455638: "rgb(179, 56, 79)", 0.0: "rgb(121, 28, 149)", 0.10870219813309245: "rgb(44, 147, 200)", 0.12623481073520415: "rgb(78, 170, 98)", 0.10298102981029811: "rgb(150, 87, 91)", 0.044263775971093045: "rgb(223, 39, 33)", 0.13340724316334074: "rgb(194, 205, 92)", 0.10034049058439304: "rgb(99, 41, 106)", 0.08040984519434236: "rgb(97, 51, 26)", 0.008130081300813009: "rgb(106, 148, 70)", 0.07158437438032918: "rgb(54, 159, 37)" } # Sort the dictionary by its numerical keys sorted_pairs = sorted(colormap_coms.items(), key=lambda x: x[0]) values = [pair[0] for pair in sorted_pairs] rgb_strings = [pair[1] for pair in sorted_pairs] # Convert RGB strings to normalized (0-1) tuples (required for Matplotlib) normalized_colors = [] for rgb in rgb_strings: # Pull out the R, G, B values and convert to 0-1 range r, g, b = map(int, rgb.strip("rgb()").split(",")) normalized_colors.append((r/255, g/255, b/255))
Step 2: Make a discrete color scale (exact matches)
If you want each value to map to its exact color with no interpolation, use ListedColormap from Matplotlib. This creates a color bar where each tick lines up perfectly with your dictionary's values.
import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap # Create the custom discrete colormap discrete_cmap = ListedColormap(normalized_colors) # Set up the color bar figure fig, ax = plt.subplots(figsize=(8, 1)) fig.subplots_adjust(bottom=0.5) # Link our values to the color scale and draw the bar value_range = plt.Normalize(min(values), max(values)) color_bar = plt.colorbar( plt.cm.ScalarMappable(norm=value_range, cmap=discrete_cmap), cax=ax, orientation="horizontal", ticks=values # Use your exact values as ticks ) # Format tick labels for readability (adjust decimal places as needed) color_bar.ax.set_xticklabels([f"{v:.4f}" for v in values]) color_bar.set_label("Corresponding Numeric Values") plt.show()
Step 3: Make a continuous color scale (interpolated)
If you want smooth transitions between your colors for values in between your dictionary's keys, use LinearSegmentedColormap instead. This creates a gradient between your defined color-value pairs.
from matplotlib.colors import LinearSegmentedColormap # Create a continuous interpolated colormap continuous_cmap = LinearSegmentedColormap.from_list( "custom_continuous", list(zip(values, normalized_colors)) # Map values directly to colors ) # Draw the continuous color bar fig, ax = plt.subplots(figsize=(8, 1)) fig.subplots_adjust(bottom=0.5) color_bar = plt.colorbar( plt.cm.ScalarMappable(norm=value_range, cmap=continuous_cmap), cax=ax, orientation="horizontal", ticks=values ) color_bar.ax.set_xticklabels([f"{v:.4f}" for v in values]) color_bar.set_label("Corresponding Numeric Values") plt.show()
Bonus: Web-friendly HTML color scale
If you need a color scale for a website or report, you can generate a simple HTML version that you can embed directly. It automatically sets text color to white/black based on background brightness for readability:
# Generate an HTML color scale html_scale = '<div style="display: flex; width: 800px; margin: 10px 0;">' for val, rgb in sorted_pairs: # Calculate brightness to pick text color r, g, b = map(int, rgb.strip("rgb()").split(",")) brightness = (r * 299 + g * 587 + b * 114) / 1000 text_color = "white" if brightness < 128 else "black" html_scale += f''' <div style="background-color: {rgb}; flex: 1; padding: 8px; text-align: center; color: {text_color};"> {val:.4f} </div> ''' html_scale += '</div>' # Print the HTML to copy-paste print(html_scale)
内容的提问来源于stack exchange,提问作者Kameron

