Modify tick label text

前端 未结 10 1478
遥遥无期
遥遥无期 2020-11-22 07:13

I want to make some modifications to a few selected tick labels in a plot.

For example, if I do:

label = axes.yaxis.get_major_ticks()[2].label
label         


        
10条回答
  •  眼角桃花
    2020-11-22 08:06

    It's been a while since this question was asked. As of today (matplotlib 2.2.2) and after some reading and trials, I think the best/proper way is the following:

    Matplotlib has a module named ticker that "contains classes to support completely configurable tick locating and formatting". To modify a specific tick from the plot, the following works for me:

    import matplotlib.pyplot as plt
    import matplotlib.ticker as mticker
    import numpy as np 
    
    def update_ticks(x, pos):
        if x == 0:
            return 'Mean'
        elif pos == 6:
            return 'pos is 6'
        else:
            return x
    
    data = np.random.normal(0, 1, 1000)
    fig, ax = plt.subplots()
    ax.hist(data, bins=25, edgecolor='black')
    ax.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
    plt.show()
    

    Caveat! x is the value of the tick and pos is its relative position in order in the axis. Notice that pos takes values starting in 1, not in 0 as usual when indexing.


    In my case, I was trying to format the y-axis of a histogram with percentage values. mticker has another class named PercentFormatter that can do this easily without the need to define a separate function as before:

    import matplotlib.pyplot as plt
    import matplotlib.ticker as mticker
    import numpy as np 
    
    data = np.random.normal(0, 1, 1000)
    fig, ax = plt.subplots()
    weights = np.ones_like(data) / len(data)
    ax.hist(data, bins=25, weights=weights, edgecolor='black')
    ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.0, decimals=1))
    plt.show()
    

    In this case xmax is the data value that corresponds to 100%. Percentages are computed as x / xmax * 100, that's why we fix xmax=1.0. Also, decimals is the number of decimal places to place after the point.

提交回复
热议问题