for use in VSCode Jupyter notebooks / lab automatically adjust which labels are shown
Last active
June 29, 2023 18:27
-
-
Save Josverl/9882787f246b8588a34280cea8c1e4fe to your computer and use it in GitHub Desktop.
Matplotlib with many text lablels decluttered.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%matplotlib widget | |
from matplotlib import ticker | |
import matplotlib.pyplot as plt | |
import numpy as np | |
fig, ax = plt.subplots(figsize=(8, 2.5)) | |
# list of desciptions for the x-axis | |
x = mi_list.np_array["description"] | |
x = [f'Step-{xx}' for xx in np.arange(100)] | |
def format_x_label(x_value, tick_pos): | |
"formatter function to retrieve the label for the x-axis based onthe x_value that is passed in." | |
try: | |
idx = int(x_value) # convert float to int | |
return x[idx] # return the label from the list | |
except IndexError: | |
return str(x_value) # out of range | |
# fake data for the y-axis | |
y = np.random.randint(0, 100, len(x)) | |
ax.plot(np.arange(len(x)), y) | |
ax.set_title("x converted to numbers --> lookup label in list[label] via formatter") | |
# nbins sets the number of major-ticks on the x-axis, integers only as these are used as index into the list | |
ax.xaxis.set_major_locator(ticker.MaxNLocator( nbins="auto", integer=True)) | |
# set the formatter function for the x-axis to replace the numbers with the labels | |
ax.xaxis.set_major_formatter(format_x_label) | |
# add minor ticks - optional but gives a hint that there are more datapoint between the major ticks | |
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) | |
for label in ax.get_xticklabels(): | |
label.set_horizontalalignment("left") | |
label.set_rotation(-10) | |
label.set_fontsize("small") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment