gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
Write code that gets an 'ax' and sorts the legend entries on it in matplotlib
- User
Write code that gets an 'ax' and sorts the legend entries on it in matplotlib
- Assistant
To sort the legend entries in a Matplotlib plot, you can extract the labels and handles from the legend, sort them, and then update the legend with the sorted entries. Here's how you can achieve that:
pythonimport matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4] y1 = [10, 20, 25, 30] y2 = [15, 18, 22, 35] y3 = [12, 28, 22, 30] # Create a plot fig, ax = plt.subplots() # Plot data with labels line1, = ax.plot(x, y1, label='B-Line') line2, = ax.plot(x, y2, label='A-Line') line3, = ax.plot(x, y3, label='C-Line') # Create the legend handles, labels = ax.get_legend_handles_labels() # Sort legend entries sorted_labels_handles = sorted(zip(labels, handles), key=lambda x: x[0]) sorted_labels, sorted_handles = zip(*sorted_labels_handles) # Update legend with sorted entries ax.legend(sorted_handles, sorted_labels) # Display the plot plt.show()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.