Search code examples
pythonmatplotlibaxis-labels

Placing ticklabels on logscale


I have a plot with an inset and I have problem setting the tick position and labels at the position that I want.

I have a graph with an inset and I have the problem with the inset. The code I have for the inset is the following:

import matplotlib.pyplot as plt 
fontsmall=16
left, bottom, width, height = [.14, 0.70, 0.16, 0.20]
ax3 = fig.add_axes([left, bottom, width, height])
plt.yscale('log')
plt.xscale('log')


ax3.set_xlim(0.6,10)
ax3.set_ylim(1,1*10**3)

xaxis=[1,10]
yaxis=np.power(xaxis,2.5)
ax3.plot(xaxis,yaxis,lw=2,color='black')

ax3.tick_params(labelleft='off',labelright='on')
ax3.yaxis.set_label_position("right")
ax3.tick_params(axis="x", pad=-0.5)
ax3.tick_params(axis='y',which='minor',left='off',right='off')
ax3.tick_params(axis='y',which='major',left='on',right='on')
ax3.set_ylabel('$K\'_0$ (Pa)',fontsize=fontsmall,rotation=270)
ax3.yaxis.labelpad = 19
ax3.xaxis.labelpad = -9
ax3.set_xlabel('$c_p$ (mg/ml)',fontsize=fontsmall)

#I want to have ticks at these positions:
ax3.yaxis.set_ticks((10**0,10**1,10**2,10**3))

#But the labels I want at position 10**1 and 10**3, in log format

#trying to remove 10**0 and 10**2, but this makes the labels in 10, and 1000 instead of the log format
#labels = [item.get_text() for item in ax3.get_yticklabels()] 
#labels[0] = ''
#labels[2] = ''
#
#ax3.set_yticklabels(labels)

#other method I came across:
a=ax3.get_yticks().tolist()
a[0]=''
a[2]=''
ax3.set_yticklabels(a)
#again, 10 and 1000 instead of the log format, when trying to change this:
ax3.yaxis.set_major_formatter(matplotlib.ticker.LogFormatter())
#now all 4 labels are visible again for some reason, and not in the 10^0  format I want
#
#

I have looked at multiple posts that want to change the placing of the ticks and the labels. However, I have not come across a post that changes both the placing of the ticklabels and change it to the correct log format that I want to have here. How could I do this?

Alternatively, I have also seen a post where they put the labels to 'invisible':

for label in ax3.get_yticklabels():
    label.set_visible(False)

but this removes all the labels, which is not what I want either. Is there a way to only select the labels I want to remove?


Solution

  • You were very close, all you want to do is turn off the visibility for two specific labels, not all of them. Hence, don't use the for loop, just do it explicitly like you were trying to do with the text.

    labels = ax3.get_yticklabels()
    labels[0].set_visible(False)
    labels[2].set_visible(False)