Python Matplotlib:如何强制使用整数刻度标签?

Python Matplotlib:如何强制使用整数刻度标签?,python,matplotlib,plot,Python,Matplotlib,Plot,我的python脚本使用matplotlib绘制x、y、z数据集的二维“热图”。我的x和y值代表蛋白质中的氨基酸残基,因此只能是整数。当我放大绘图时,它如下所示: 正如我所说,x-y轴上的浮点值对我的数据没有意义,因此我希望它看起来像这样: 有什么办法可以做到这一点吗? 这是生成绘图的代码: def plotDistanceMap(self): # Read on x,y,z x = self.currentGraph['xData'] y = self.curren

我的python脚本使用matplotlib绘制x、y、z数据集的二维“热图”。我的x和y值代表蛋白质中的氨基酸残基,因此只能是整数。当我放大绘图时,它如下所示:

正如我所说,x-y轴上的浮点值对我的数据没有意义,因此我希望它看起来像这样:

有什么办法可以做到这一点吗? 这是生成绘图的代码:

def plotDistanceMap(self):
    # Read on x,y,z
    x = self.currentGraph['xData']
    y = self.currentGraph['yData']
    X, Y = numpy.meshgrid(x, y)
    Z = self.currentGraph['zData']
    # Define colormap
    cmap = colors.ListedColormap(['blue', 'green', 'orange', 'red'])
    cmap.set_under('white')
    cmap.set_over('white')
    bounds = [1,15,50,80,100]
    norm = colors.BoundaryNorm(bounds, cmap.N)
    # Draw surface plot
    img = self.axes.pcolor(X, Y, Z, cmap=cmap, norm=norm)
    self.axes.set_xlim(x.min(), x.max())
    self.axes.set_ylim(y.min(), y.max())
    self.axes.set_xlabel(self.currentGraph['xTitle'])
    self.axes.set_ylabel(self.currentGraph['yTitle'])
    # Cosmetics
    #matplotlib.rcParams.update({'font.size': 12})
    xminorLocator = MultipleLocator(10)
    yminorLocator = MultipleLocator(10)
    self.axes.xaxis.set_minor_locator(xminorLocator)
    self.axes.yaxis.set_minor_locator(yminorLocator)
    self.axes.tick_params(direction='out', length=6, width=1)
    self.axes.tick_params(which='minor', direction='out', length=3, width=1)
    self.axes.xaxis.labelpad = 15
    self.axes.yaxis.labelpad = 15
    # Draw colorbar
    colorbar = self.figure.colorbar(img, boundaries = [0,1,15,50,80,100], 
                                    spacing = 'proportional',
                                    ticks = [15,50,80,100], 
                                    extend = 'both')
    colorbar.ax.set_xlabel('Angstrom')
    colorbar.ax.xaxis.set_label_position('top')
    colorbar.ax.xaxis.labelpad = 20
    self.figure.tight_layout()      
    self.canvas.draw()
根据对的回答,我提出了一个解决方案,不知道它是否能在您的情况下工作,因为您的代码片段本身无法执行

其思想是强制记号标签的间距为.5,然后用整数替换每一个.5记号,用空字符串替换其他记号

import numpy
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1,2)

x1, x2 = 1, 5
y1, y2 = 3, 7

# first axis: ticks spaced at 0.5
ax1.plot([x1, x2], [y1, y2])
ax1.set_xticks(numpy.arange(x1-1, x2+1, 0.5))
ax1.set_yticks(numpy.arange(y1-1, y2+1, 0.5))

# second axis: tick labels will be replaced
ax2.plot([x1, x2], [y1, y2])
ax2.set_xticks(numpy.arange(x1-1, x2+1, 0.5))
ax2.set_yticks(numpy.arange(y1-1, y2+1, 0.5))

# We need to draw the canvas, otherwise the labels won't be positioned and 
# won't have values yet.
fig.canvas.draw()

# new x ticks  '1'->'', '1.5'->'1', '2'->'', '2.5'->'2' etc.
labels = [item.get_text() for item in ax2.get_xticklabels()]
new_labels = [ "%d" % int(float(l)) if '.5' in l else '' for l in labels]
ax2.set_xticklabels(new_labels)

# new y ticks
labels = [item.get_text() for item in ax2.get_yticklabels()]
new_labels = [ "%d" % int(float(l)) if '.5' in l else '' for l in labels]
ax2.set_yticklabels(new_labels)

fig.canvas.draw()
plt.show()

如果你想放大很多,那就需要格外小心,因为这张照片会产生一组非常密集的记号标签。

这应该更简单:

(来自)


通过简单地将索引
i
转换为字符串,以下解决方案对我有效:

导入matplotlib.pyplot作为plt
导入时间
datay=[1,6,8,4]#只是一个例子
数据x=[]
#在下面的for循环中,最后的datax将具有相同大小的datay,
#可以通过将范围替换为所需的任何值来进行更改
对于范围内的i(len(datay)):
#在下面的赋值语句中,datax中的每个值
#列表将设置为字符串,这解决了浮点问题
datax+=[str(1+i)]
a=plt
#plot函数将datax内容设置为x刻度,即datay值
#用作要绘制的实际值
a、 绘图(数据X、数据Y)
a、 show()

对于我来说,它不会将记号标签放在给定区域的中间点(如问题的示例图像),并且每秒(未标记的)记号都会丢失。有没有一个简单的技巧来实现这些?“2”应该位于2.5的位置,而不是2.0的位置。@Andris哇,关于这一点我完全不知道。但无论如何,为这项任务调整绘图库似乎很奇怪,您可能应该改为修改数据。您所指的示例图像似乎是使用paint或类似工具编辑的,因此这并不意味着matplotlib可以进行此类输出。这给了我非常奇怪的结果。它将滴答声[0,2,4,8,10]转换为[0.0,1.5,3.0,4.5,7.5,9.0,10.5]。考虑到大家所说的,这是不应该发生的。大家好,欢迎来到SO!
datax
对应什么?您没有共享代码来设置记号标签,因此不清楚
datax
是x记号还是y记号的标签列表(对应于
datay
变量)。例如,如果OP的x变量范围为1到15,我看不出这将如何工作。我建议你让你的答案适用于任何范围的价值观,就像目前被接受的答案一样。鉴于您是一个新用户,我暂时不否决这个答案,但我鼓励您尽快改进它。谢谢您的建议!我的错,我急忙回答,现在让我知道答案是否正确!将整数列表转换为str列表=>
list(map(str,list_int))
@Andris'提供了相同的基本建议,但还有大量用于上下文的附加代码。
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
#...
ax = plt.figure().gca()
#...
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_xticks([2,3])
ax.set_yticks([2,3])