Python | Matplotlib.pyplot ticks

Python | Matplotlib.pyplot ticks

In matplotlib, ticks refer to the values and their corresponding labels on the axes of a plot. The pyplot module provides various functions to modify and customize these ticks.

Here are some useful functions and techniques related to ticks:

  1. Setting tick locations:

    Using xticks() and yticks(), you can specify the positions of the ticks on the x and y axes, respectively.

    import matplotlib.pyplot as plt plt.plot([0, 1, 2], [0, 1, 2]) plt.xticks([0, 0.5, 1, 1.5, 2]) plt.yticks([0, 1, 2]) plt.show() 
  2. Setting tick labels:

    You can also provide labels for the specified tick positions.

    plt.plot([0, 1, 2], [0, 1, 4]) plt.xticks([0, 1, 2], ['zero', 'one', 'two']) plt.yticks([0, 1, 4], ['zero', 'one', 'four']) plt.show() 
  3. Rotating tick labels:

    Sometimes, especially with x-axis labels, there may be overlap. You can rotate labels for clarity.

    plt.plot([0, 1, 2], [0, 1, 2]) plt.xticks([0, 1, 2], ['zero', 'one', 'two'], rotation=45) plt.show() 
  4. Using tick formatters:

    For more complex formatting needs, you can use FuncFormatter.

    from matplotlib.ticker import FuncFormatter def format_func(value, tick_number): return f'{value:.2f}' fig, ax = plt.subplots() ax.plot([0, 1, 2], [0, 1, 4]) ax.xaxis.set_major_formatter(FuncFormatter(format_func)) plt.show() 
  5. Hiding ticks or labels:

    If you don't want to display ticks or labels, you can turn them off.

    plt.plot([0, 1, 2], [0, 1, 2]) plt.yticks([]) # Hide y-axis ticks plt.xticks([0, 1, 2], ['zero', 'one', 'two'], visible=False) # Hide x-axis labels but not ticks plt.show() 
  6. Setting tick intervals:

    You can use MultipleLocator to set regular intervals for ticks.

    from matplotlib.ticker import MultipleLocator fig, ax = plt.subplots() ax.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16]) ax.xaxis.set_major_locator(MultipleLocator(1)) ax.yaxis.set_major_locator(MultipleLocator(5)) plt.show() 

These are just a few examples of what you can do with ticks in matplotlib.pyplot. Depending on your specific needs, there are many more customizations available.


More Tags

assets contour buffer embedded-resource skew patch days dhtml proxy-authentication jenkins-scriptler

More Programming Guides

Other Guides

More Programming Examples