使用matplotlib打印时更改刻度标签的位置(移动)

2024-06-28 23:55:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在和matplotlib密谋。代码如下(zvals具有这些值)

cmap = mpl.colors.ListedColormap(['darkblue', 'blue', 'lightblue','lightgreen','yellow','gold','orange','darkorange','orangered','red'])
bounds=[0, 10,20,30,40,50,60,70,80,100,200,1000]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
img2 = plt.imshow(zvals,interpolation='nearest',
                cmap = cmap,
                norm=norm,
                origin='lower')


xlocations = na.array(range(30)) + 0.5
xticks(xlocations, [str(x+1) for x in arange(30)], rotation=0, size=5)
gca().xaxis.set_ticks_position('none')
gca().yaxis.set_ticks_position('none')  
grid(True)

结果如下: http://imageshack.us/a/img145/7325/histogrammoverview.png

我想把xtick(1,2,3,…)的标签移到左边一点,这样它们就在相应的颜色框下面。相应地,我也希望将yticks(user1和user2)的标签向下移动一点,以便正确显示它们。怎么能做到?

编辑:事实上我可以更改下面的行 xlocations=na.数组(范围(30))+0.5 到 xlocations=na.数组(范围(30))

然后生成的图片如下: http://imageshack.us/a/img338/7325/histogrammoverview.png

请注意网格正在“穿过”彩色框,这不是我想要的。我想用网格把上面图片中的彩色框边起来。在这个版本中,标签(1,2,3,…)被正确地放在盒子下面。我怎样才能正确地放置标签(在彩色框的下面)和一个围绕着彩色框而不是穿过彩色框中间的网格。

解决方案

此解决方案有效(如答案所示):

periods = 30
xlocations = na.array(range(periods))
xminorlocations = na.array(range(periods))+0.5
xticks(xlocations, [str(x+1) for x in arange(periods)], rotation=0, size=5)
plt.set_xticks(xminorlocations, minor=True)
grid(True, which='minor', linestyle='-')

结果:hxxp://imageshack.us/a/img9/7325/histogrammoverview.png


Tags: truenormrange标签array彩色cmapus
1条回答
网友
1楼 · 发布于 2024-06-28 23:55:10

我认为你可以通过

  • 将主要刻度位置设置为每个正方形的中间。
  • 将次要刻度设置为每个正方形的边缘。
  • 将网格设置为仅在小刻度中显示。

网格只能在使用

plt.grid(True, which='minor')

我也会将行样式设置为'-'

相关问题 更多 >