Matplotlib: Move ticklabels between ticks

前端 未结 2 1932
北恋
北恋 2020-12-31 01:38

I want to create a visualization of a confusion matrix using matplotlib. Parameters to the methods shown below are the class labels (alphabet), the classification results as

相关标签:
2条回答
  • 2020-12-31 01:55

    Alternatively: have you tried im = ax.matshow(data, cmap='gray') instead of imshow()? This should also place the ticklabels on the correct position.

    0 讨论(0)
  • 2020-12-31 02:02

    As you've noticed, they're centered by default and you're overriding the default behavior by specifying extent=[0, width, height, 0].

    There are a number of ways to handle this. One is to use pcolor and set the edgecolors and linestyles to look like the gridlines (you actually need pcolor and not pcolormesh for this to work). However, you'll have to change the extents to get the ticks in the center as imshow does by default.

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = np.random.random((10,10))
    labels = 'abcdefghij'
    
    fig, ax = plt.subplots()
    im = ax.pcolor(data, cmap='gray', edgecolor='black', linestyle=':', lw=1)
    fig.colorbar(im)
    
    # Shift ticks to be at 0.5, 1.5, etc
    for axis in [ax.xaxis, ax.yaxis]:
        axis.set(ticks=np.arange(0.5, len(labels)), ticklabels=labels)
    
    plt.show()
    

    enter image description here

    Alternatively, you could turn on the minor grid and place it at the pixel boundaries. Because you want fixed labels, we'll just set everything manually. Otherwise, a MultipleLocator would make more sense:

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = np.random.random((10,10))
    labels = 'abcdefghij'
    
    fig, ax = plt.subplots()
    im = ax.imshow(data, cmap='gray', interpolation='none')
    fig.colorbar(im)
    
    # Set the major ticks at the centers and minor tick at the edges
    locs = np.arange(len(labels))
    for axis in [ax.xaxis, ax.yaxis]:
        axis.set_ticks(locs + 0.5, minor=True)
        axis.set(ticks=locs, ticklabels=labels)
    
    # Turn on the grid for the minor ticks
    ax.grid(True, which='minor')
    
    plt.show()
    

    enter image description here

    0 讨论(0)
提交回复
热议问题