【问题标题】:Change grid interval and specify tick labels in Matplotlib在 Matplotlib 中更改网格间隔并指定刻度标签
【发布时间】:2014-07-24 21:07:48
【问题描述】:

我正在尝试在网格图中绘制计数,但我无法弄清楚如何去做。

我想要:

  1. 以 5 为间隔的点状网格;

  2. 每 20 个主要刻度标签;

  3. 刻度线位于绘图之外;和

  4. 在这些网格中进行“计数”。

我已经检查了潜在的重复项,例如 herehere,但无法弄清楚。

这是我的代码:

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

for key, value in sorted(data.items()):
    x = value[0][2]
    y = value[0][3]
    count = value[0][4]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.annotate(count, xy = (x, y), size = 5)
    # overwrites and I only get the last data point

    plt.close()
    # Without this, I get a "fail to allocate bitmap" error.

plt.suptitle('Number of counts', fontsize = 12)
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.axes().set_aspect('equal')

plt.axis([0, 1000, 0, 1000])
# This gives an interval of 200.

majorLocator   = MultipleLocator(20)
majorFormatter = FormatStrFormatter('%d')
minorLocator   = MultipleLocator(5)
# I want the minor grid to be 5 and the major grid to be 20.
plt.grid()

filename = 'C:\Users\Owl\Desktop\Plot.png'
plt.savefig(filename, dpi = 150)
plt.close()

这就是我得到的。

我也遇到了数据点被覆盖的问题。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: python matplotlib plot grid label


    【解决方案1】:

    MaxNoe's answer 的微妙替代方案,您无需显式设置节拍而是设置节奏。

    import matplotlib.pyplot as plt
    from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
    
    fig, ax = plt.subplots(figsize=(10, 8))
    
    # Set axis ranges; by default this will put major ticks every 25.
    ax.set_xlim(0, 200)
    ax.set_ylim(0, 200)
    
    # Change major ticks to show every 20.
    ax.xaxis.set_major_locator(MultipleLocator(20))
    ax.yaxis.set_major_locator(MultipleLocator(20))
    
    # Change minor ticks to show every 5. (20/4 = 5)
    ax.xaxis.set_minor_locator(AutoMinorLocator(4))
    ax.yaxis.set_minor_locator(AutoMinorLocator(4))
    
    # Turn grid on for both major and minor ticks and style minor slightly
    # differently.
    ax.grid(which='major', color='#CCCCCC', linestyle='--')
    ax.grid(which='minor', color='#CCCCCC', linestyle=':')
    

    【讨论】:

    • 谢谢!这更实用。
    • 这个我找了很久
    【解决方案2】:

    您的代码中有几个问题。

    首先是大的:

    1. 您正在循环的每次迭代中创建一个新图形和一个新轴 → 将fig = plt.figureax = fig.add_subplot(1,1,1) 放在循环之外。

    2. 不要使用定位器。使用正确的关键字调用函数ax.set_xticks()ax.grid()

    3. 使用plt.axes(),您将再次创建新轴。使用ax.set_aspect('equal')

    小事: 您不应将 plt.axis() 等类似 MATLAB 的语法与目标语法混合使用。 使用ax.set_xlim(a,b)ax.set_ylim(a,b)

    这应该是一个工作最小的例子:

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    
    # Major ticks every 20, minor ticks every 5
    major_ticks = np.arange(0, 101, 20)
    minor_ticks = np.arange(0, 101, 5)
    
    ax.set_xticks(major_ticks)
    ax.set_xticks(minor_ticks, minor=True)
    ax.set_yticks(major_ticks)
    ax.set_yticks(minor_ticks, minor=True)
    
    # And a corresponding grid
    ax.grid(which='both')
    
    # Or if you want different settings for the grids:
    ax.grid(which='minor', alpha=0.2)
    ax.grid(which='major', alpha=0.5)
    
    plt.show()
    

    输出是这样的:

    【讨论】:

    • 非常感谢您的回答!你解决了我的问题!要在外面设置刻度,我只需要添加 ax.tick_params(which = 'both', direction = 'out')。
    • 已经投票了,但你能告诉我ax.set_xticks(minor_ticks, minor=True)ax.set_yticks(minor_ticks, minor=True) 存在时ax.set_xticks(major_ticks)ax.set_yticks(major_ticks) 的用途是什么吗?谢谢。
    • @Codist 因为主要和次要刻度需要单独设置。请参阅此处的文档:matplotlib.org/3.5.1/api/_as_gen/…
    猜你喜欢
    • 2014-02-27
    • 1970-01-01
    • 2015-05-25
    • 2011-09-23
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    相关资源
    最近更新 更多