I am trying to create a plot but I just want the ticklabels to show as shown where the log scale is shown as above. I only want the minor ticklabel for 50, 500 and 2000 to s
1) Use FixedLocator
to statically define explicit tick locations.
2) Colorbar cbar
will have an ax
attribute that will provide access to the usual axis methods including tick formatting.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(10,3000,100)
y = np.arange(10,3000,100)
X,Y = np.meshgrid(x,y)
Z = np.random.random(X.shape)*8000000
surf = ax.contourf(X,Y,Z, 8, cmap=plt.cm.jet)
ax.set_ylabel('Log Frequency (Hz)')
ax.set_xlabel('Log Frequency (Hz)')
ax.set_xscale('log')
ax.set_yscale('log')
ax.xaxis.set_minor_formatter(plt.FormatStrFormatter('%d'))
# defining custom minor tick locations:
ax.xaxis.set_minor_locator(plt.FixedLocator([50,500,2000]))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.tick_params(axis='both',reset=False,which='both',length=8,width=2)
cbar = fig.colorbar(surf, shrink=0.5, aspect=20, fraction=.12,pad=.02)
cbar.set_label('Activation',size=18)
# access to cbar tick labels:
cbar.ax.tick_params(labelsize=5)
plt.show()
Edit
If you want the tick marls, but you want to selectively show the labels, I see nothing wrong with your iteration, except I might use set_visible
instead of making the fontsize zero.
You might enjoy finer control using a FuncFormatter
where you can use the value or position of the tick to decide whether it gets shown:
def show_only_some(x, pos):
s = str(int(x))
if s[0] in ('2','5'):
return s
return ''
ax.xaxis.set_minor_formatter(plt.FuncFormatter(show_only_some))
Based on the answer from @Paul I created the following function:
def get_formatter_function(allowed_values, datatype='float'):
"""returns a function, which only allows allowed_values as axis tick labels"""
def hide_others(value, pos):
if value in allowed_values:
if datatype == 'float':
return value
elif datatype == 'int':
return int(value)
return ''
return hide_others
Which is a bit more flexible.