pyplot cmap上的格式化滴答失败了

时间:2018-01-23 16:12:44

标签: python matplotlib

使用以下代码: -

fig=plt.figure()
#ax = fig.add_subplot(111)
ax=plt.axes()
font0 = FontProperties()

outgrid=[[x*y for x in range(testXaxis)] for y in range (levIndRange)]
vmin=0
vmax=testXaxis*levIndRange
height = [v*1000.5 for v in range (levMaxInd)]

colours='terrain'
cmap=plt.cm.get_cmap(colours)
norm=matplotlib.colors.Normalize(clip=False,vmin=vmin,vmax=vmax)
print 'vmax = ',vmax
m=plt.cm.ScalarMappable(cmap=cmap,norm=norm)  
m.set_array(outgrid)
plt.imshow(np.flipud(outgrid),cmap=cmap, norm=norm, aspect=stretch)
#ax.imshow(np.flipud(outgrid),cmap=cmap, norm=norm, aspect=stretch)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
#plt.axis.YAxis.set_major_formatter(FormatStrFormatter('%.0f')) # 'module' object has no attribute 'set_major_formatter'
plt.yticks([s for s in range(0,levIndRange,levParInt)],[height[v] for v in range(levMinInd-1,levMaxInd-1,levParInt)])
plt.xticks([1,3,5,7,9,11,13,15,17,19])
#ax.xaxis.set_ticks([1,3,5,7,9,11,13,15,17,19])
#ax.yaxis.set_ticks([height[v] for v in range(levMinInd-1,levMaxInd-1,levParInt)])    # This one line makes the plot collapse
plt.ylabel(yLabel)
plt.xlabel(xLabel)

我得到以下情节,这很好,但我想改变y轴上的浮点精度: -

Plot with default floating precision

所以,当我尝试使用set_major_formatter改变y轴的精度时,使用以下几行代替plot.yticks: -

ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
ax.xaxis.set_ticks([1,3,5,7,9,11,13,15,17,19])
ax.yaxis.set_ticks([height[v] for v in range(levMinInd-1,levMaxInd-1,levParInt)])    # This one line makes the plot collapse

......情节消失了: -

Plot with formatted floating precision

如何在不丢失情节的情况下改变精度?

感激不尽的任何帮助。 感谢

1 个答案:

答案 0 :(得分:0)

我正在回答而不是编辑,因为我已经解决了丢失的情节问题,这可能对其他人有所帮助。解决方案是在ax.yaxis.set_ticks行之后移动plt.imshow行。但是,我仍然没有得到没有小数点的预期Y轴刻度。

下面的第一个代码块产生一个Y刻度的图:0.0,1000.5,2001.0,3001.5,4002.0

import matplotlib
import matplotlib.pyplot as plt
outgrid=[[x*y for x in range(4)] for y in range (5)]
height = [v*1000.5 for v in range (5)]
cmap=plt.cm.get_cmap('terrain')
norm=matplotlib.colors.Normalize(clip=False)
m=plt.cm.ScalarMappable(cmap=cmap,norm=norm)  
m.set_array(outgrid)
plt.imshow(outgrid,cmap=cmap, norm=norm, aspect=0.5)
plt.yticks([s for s in range(5)],[height[t] for t in range(5)])
plt.show() 

第二个代码块尝试格式化这些刻度而没有小数点,但只生成一个Y刻度为0

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
ax=plt.axes()
outgrid=[[x*y for x in range(4)] for y in range (5)]
height = [v*1000.5 for v in range (5)]
cmap=plt.cm.get_cmap('terrain')
norm=matplotlib.colors.Normalize(clip=False)
m=plt.cm.ScalarMappable(cmap=cmap,norm=norm)  
m.set_array(outgrid)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
ax.yaxis.set_ticks([height[t] for t in range(5)])    
plt.imshow(outgrid,cmap=cmap, norm=norm, aspect=0.5)
plt.show()