You're right, hsv (and some other cyclical colormaps) can have similar colors at their beginning and end, which can make the first and last lines hard to distinguish.
To address this, I'll switch to the gist_rainbow colormap. It's designed to provide a wide range of perceptually distinct hues, which is generally better for many categorical lines. I'll also slightly adjust the linspace range to avoid the absolute ends of the colormap, just in case, though gist_rainbow is less prone to the red-to-red wrap-around problem than hsv.
python
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Load the TSV file
df = pd.read_csv('average_deltas_by_box.tsv', sep='\t')
# Get the delta columns
delta_cols = [col for col in df.columns if col.startswith('delta')]
# Extract delta values from column names (e.g., 'delta10' -> 10)
delta_values = []
for col in delta_cols:
delta_val = int(col.replace('delta', ''))
delta_values.append(delta_val)
# Prepare for plotting
plt.figure(figsize=(12, 8))
# Generate colors for each box using 'gist_rainbow'
# Adjust linspace slightly to avoid extreme ends if necessary, though 'gist_rainbow' is less sensitive
num_boxes = len(df)
colors = plt.cm.get_cmap('gist_rainbow', num_boxes) # Use get_cmap for specific colormaps, directly provide num_colors
# Plot each box as a line
for i, row in df.iterrows():
# Use f-string to create a clear label for the legend
box_label = f"Box [{row['box_start']}, {row['box_end']})"
y_values = [row[col] for col in delta_cols]
plt.plot(delta_values, y_values, label=box_label, color=colors(i), marker='o', markersize=4, linestyle='-') # Added markersize
# Add labels, title, and grid
plt.xlabel('Delta')
plt.ylabel('Average Value')
plt.title('Average Values by Delta for Each Box')
plt.grid(True)
# Position the legend outside the plot on the right side with 2 columns
# Adjust bbox_to_anchor and right margin slightly if needed based on the number of labels
plt.legend(bbox_to_anchor=(1.02, 0.5), loc='center left', ncol=2, fontsize='small')
# Adjust layout to make room for the legend
plt.tight_layout()
plt.subplots_adjust(right=0.75) # This value might need slight tweaking depending on the number of boxes/labels
# Save the plot
plt.savefig('boxes_as_lines_plot_improved_colors.png', bbox_inches='tight')
plt.show()
print(f"Plot saved as 'boxes_as_lines_plot_improved_colors.png' with {len(df)} box lines and improved color distinction.")
Key Change:
colors = plt.cm.get_cmap('gist_rainbow', num_boxes): This directly requests num_boxes distinct colors from the gist_rainbow colormap. gist_rainbow is generally much better at providing a wide range of hues across its spectrum, which helps with distinguishing many lines.
This change should result in much more distinguishable colors for all lines, especially for the first and last boxes.