Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: How to remove ticks&tick values from secondary axis?

I have this code for a graph, and I do not want the values & ticks on the top and right axes.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()


#Set axis labels
ax.set_xlabel('NEGATIVE')
ax.set_ylabel('HAPPY')
ax2 = ax.secondary_xaxis('top')
ax2.set_xlabel('POSITIVE')
ax2 = ax.secondary_yaxis('right')
ax2.set_ylabel('SAD')


#Remove ticks/values
ax.set_yticklabels([])
ax.set_xticklabels([])
ax.set_yticks([])
ax.set_xticks([])
ax2.set_yticklabels([])
ax2.set_xticklabels([])
ax2.set_yticks([])
ax2.set_xticks([])

#Show graph
plt.show()

it's showing it like this: image of graph


2 Answers

Use tick_params to manipulate the axis ticks and labels:

import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()

#Set axis labels
ax1.set_xlabel('NEGATIVE')
ax1.set_ylabel('HAPPY')
ax2 = ax1.secondary_xaxis('top')
ax2.set_xlabel('POSITIVE')
ax3 = ax1.secondary_yaxis('right')
ax3.set_ylabel('SAD')

#Remove ticks/values
for ax in (ax1, ax2, ax3):
    ax.tick_params(left=False, labelleft=False, top=False, labeltop=False,
                   right=False, labelright=False, bottom=False, labelbottom=False)

#Show graph
plt.show()

A comment asked for how to only turn top and left ticks and labels off. This would be

for ax in (ax1, ax2, ax3):
    ax.tick_params(top=False, labeltop=False, right=False, labelright=False)
like image 103
ImportanceOfBeingErnest Avatar answered Feb 22 '26 21:02

ImportanceOfBeingErnest


Interesting why SecondaryAxis doesn't accept tick params, however let's use twinx and twiny:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()


#Set axis labels
ax.set_xlabel('NEGATIVE')
ax.set_ylabel('HAPPY')
ax2x = ax.twiny()
ax2.set_yticks([])
ax2x.set_xlabel('POSITIVE')
ax2y = ax.twinx()
ax2y.set_ylabel('SAD')


ax2x.set_xticks([])
ax2y.set_yticks([])
#Show graph
plt.show()

Output:

enter image description here

like image 30
Scott Boston Avatar answered Feb 22 '26 21:02

Scott Boston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!