3

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 2

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

What if you want bottom on and top off? I couldn't figure out how to just turn on bottom and left only using SecondaryAxis.
Great. Thank you! +1
1

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

1 Comment

I was struggling to understand the twinx/twiny before, but this makes much more sense! Thanks so much. <3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.