Python 在 Matplotlib 中更改网格间隔并指定刻度标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24943991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:29:59  来源:igfitidea点击:

Change grid interval and specify tick labels in Matplotlib

pythonmatplotlibplotgridlabel

提问by owl

I am trying to plot counts in gridded plots, but I am not being able to figure out how I go about it. I want to:

我试图在网格图中绘制计数,但我无法弄清楚我是如何去做的。我想要:

  1. Have dotted grids at an interval of 5

  2. Have major tick labels only every 20

  3. I want the ticks to be outside the plot.

  4. Have "counts" inside those grids

  1. 有间隔为 5 的虚线网格

  2. 只有每 20 个主要刻度标签

  3. 我希望刻度线在情节之外。

  4. 在这些网格内有“计数”

I have checked for potential duplicates such as hereand here, but I have not been able to figure it out.

我已经检查过这里这里等潜在的重复项,但我无法弄清楚。

This is my code.

这是我的代码。

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 "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 minor grid to be 5 and major grid to be 20
plt.grid()

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

This is what I get.

这就是我得到的。

This is what I get.

这就是我得到的。

I also have a problem of overwriting the data points, which I am also having trouble with... Could anybody PLEASE help me with this problem?

我也有覆盖数据点的问题,我也遇到了问题......有人可以帮我解决这个问题吗?

采纳答案by MaxNoe

There are several problems in your code.

您的代码中有几个问题。

First the big ones:

首先是大的:

  1. You are creating a new figure and a new axes in every iteration of your loop → put fig = plt.figureand ax = fig.add_subplot(1,1,1)outside of the loop.

  2. Don't use the Locators. Call the functions ax.set_xticks()and ax.grid()with the correct keywords.

  3. With plt.axes()you are creating a new axes again. Use ax.set_aspect('equal').

  1. 您正在创建一个新的人物,在你的循环→把每一次迭代一个新的轴fig = plt.figureax = fig.add_subplot(1,1,1)环路以外。

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

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

The minor things: You should not mix the MATLAB-like syntax like plt.axis()with the objective syntax. Use ax.set_xlim(a,b)and ax.set_ylim(a,b)

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

This should be a working minimal example:

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

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()

Output is this:

输出是这样的:

result

结果

回答by getup8

A subtle alternative to MaxNoe's answerwhere you aren't explicitly setting the ticks but instead setting the cadence.

MaxNoe 答案的一种微妙替代方法,您没有明确设置刻度,而是设置节奏。

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=':')

Matplotlib Custom Grid

Matplotlib 自定义网格