如何改变minorticks的数量?

时间:2014-11-05 22:19:52

标签: python matplotlib

我想创建这样的数字(https://lh3.googleusercontent.com/-DCFuRHtqTmk/VFq_cf0Cj4I/AAAAAAAAETA/hDPE8N8LLDE/w682-h695-no/figure.png),使用PLT.MATSHOW标记majorticks(范围从0到20,步长= 1),未标记的minorticks(从0.5到18.5,步长= 1)和minorgrids

这是我的代码,但它出了问题(它绘制了比我需要的更多的行,我不知道如何更改minorticks的数量):

import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt

S0 = np.ones([20,20], int)
S = np.copy(S0)
Mx = np.shape(S)[0]
My = np.shape(S)[1]

for x in range(Mx):
    for y in range(My):
            S[x,y]=2*random.randint(2)-1

plt.matshow(S, fignum = None, alpha = 0.75, cmap = "summer")
plt.xticks(range(0, Mx, 1))
plt.yticks([i for i in range(0, My)])
plt.grid(which = 'minor', ls = '-')
plt.minorticks_on()
plt.show()

我应该如何重写它来解决我的问题? 感谢您的帮助! (:

2 个答案:

答案 0 :(得分:1)

我相信这可以解决你的问题。

import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt

S0 = np.ones([20,20], int)
S = np.copy(S0)
Mx = np.shape(S)[0]
My = np.shape(S)[1]

for x in range(Mx):
    for y in range(My):
            S[x,y]=2*random.randint(2)-1

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

ax.matshow(S,alpha=0.75, cmap="summer", interpolation="none")

ax.set_xticks([i+0.5 for i in range(Mx)])
ax.set_yticks([i+0.5 for i in range(My)])

ax.set_xticklabels(range(Mx))
ax.set_yticklabels(range(My))

#plt.grid(which = 'minor', ls = '-')
plt.grid(which = 'major', ls = '-')

plt.minorticks_on()
plt.show()

我所做的改变是三重的;第一个用主网格线替换网格,第二个是我将刻度线和相应的标签移动0.5,以便它们匹配边界。第三是删除matshow命令中的插值。这一切都给出了这个:

enter image description here

答案 1 :(得分:0)

我终于找到了如何解决问题并获得我想要的东西。感谢Will,求助! 如果其他人知道如何使用不同的方法获得最终结果,如果您让我知道,我会很乐意。

这是新代码:

import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, AutoMinorLocator

S0 = np.ones([20,20], int)
S = np.copy(S0)
Mx = np.shape(S)[0]
My = np.shape(S)[1]

for x in range(Mx):
    for y in range(My):
            S[x,y]=2*random.randint(2)-1

fig = plt.figure()
ax = fig.add_subplot(111)
ax.matshow(S, alpha = .75, cmap = "summer")

ax.set_xticklabels(range(-1,Mx))
ax.set_yticklabels(range(-1,My))

ax.xaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
ax.xaxis.grid(True,'minor', lw = 1.5, ls = '-')
ax.yaxis.grid(True,'minor', lw = 1.5, ls = '-')

plt.show()