Python hide ticks but show tick labels - python

I can remove the ticks with
ax.set_xticks([])
ax.set_yticks([])
but this removes the labels as well. Any way I can plot the tick labels but not the ticks and the spine

You can set the tick length to 0 using tick_params (http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1],[1])
ax.tick_params(axis=u'both', which=u'both',length=0)
plt.show()

Thanks for your answers #julien-spronck and #cmidi.
As a note, I had to use both methods to make it work:
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(11, 3))
data = np.random.random((4, 4))
ax1.imshow(data)
ax1.set(title='Bad', ylabel='$A_y$')
# plt.setp(ax1.get_xticklabels(), visible=False)
# plt.setp(ax1.get_yticklabels(), visible=False)
ax1.tick_params(axis='both', which='both', length=0)
ax2.imshow(data)
ax2.set(title='Somewhat OK', ylabel='$B_y$')
plt.setp(ax2.get_xticklabels(), visible=False)
plt.setp(ax2.get_yticklabels(), visible=False)
# ax2.tick_params(axis='both', which='both', length=0)
ax3.imshow(data)
ax3.set(title='Nice', ylabel='$C_y$')
plt.setp(ax3.get_xticklabels(), visible=False)
plt.setp(ax3.get_yticklabels(), visible=False)
ax3.tick_params(axis='both', which='both', length=0)
plt.show()

While attending a coursera course on Python, this was a question.
Below is the given solution, which I think is more readable and intuitive.
ax.tick_params(top=False,
bottom=False,
left=False,
right=False,
labelleft=True,
labelbottom=True)

This worked for me:
plt.tick_params(axis='both', labelsize=0, length = 0)

matplotlib.pyplot.setp(*args, **kwargs) is used to set properties of an artist object. You can use this in addition to get_xticklabels() to make it invisible.
something on the lines of the following
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(2,1,1)
ax.set_xlabel("X-Label",fontsize=10,color='red')
plt.setp(ax.get_xticklabels(),visible=False)
Below is the reference page
http://matplotlib.org/api/pyplot_api.html

You can set the yaxis and xaxis set_ticks_position properties so they just show on the left and bottom sides, respectively.
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
Furthermore, you can hide the spines as well by setting the set_visible property of the specific spine to False.
axes[i].spines['right'].set_visible(False)
axes[i].spines['top'].set_visible(False)

This Worked out pretty well for me! try it out
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
languages =['Python', 'SQL', 'Java', 'C++', 'JavaScript']
pos = np.arange(len(languages))
popularity = [56, 39, 34, 34, 29]
plt.bar(pos, popularity, align='center')
plt.xticks(pos, languages)
plt.ylabel('% Popularity')
plt.title('Top 5 Languages for Math & Data \nby % popularity on Stack Overflow',
alpha=0.8)
# remove all the ticks (both axes),
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off',
labelbottom='on')
plt.show()

Currently came across the same issue, solved as follows on version 3.3.3:
# My matplotlib ver: 3.3.3
ax.tick_params(tick1On=False) # "for left and bottom ticks"
ax.tick_params(tick2On=False) # "for right and top ticks, which are off by default"
Example:
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
ax.tick_params(tick1On=False)
plt.show()
Output:

Assuming that you want to remove some ticks on the Y axes and only show the yticks that correspond to the ticks that have values higher than 0 you can do the following:
from import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# yticks and yticks labels
yTicks = list(range(26))
yTicks = [yTick if yTick % 5 == 0 else 0 for yTick in yTicks]
yTickLabels = [str(yTick) if yTick % 5 == 0 else '' for yTick in yTicks]
Then you set up your axis object's Y axes as follow:
ax.yaxis.grid(True)
ax.set_yticks(yTicks)
ax.set_yticklabels(yTickLabels, fontsize=6)
fig.savefig('temp.png')
plt.close()
And you'll get a plot like this:

Related

yticks have unexpectedly variable font size

I am modifying the yticks font size of a figure but not all yticks are of the same font size. The last two yticks 0.8 and 0.6 are greater than the others.
def mm_to_inch(value):
return value/25.4
import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['font.sans-serif'] = "Arial"
matplotlib.rcParams['font.family'] = "sans-serif"
matplotlib.rcParams['figure.dpi'] = 300
import pandas as pd
import matplotlib.pyplot as plt
size = 112
fig, ax1 = plt.subplots(figsize=(mm_to_inch(size), mm_to_inch(size/2)))
df = pd.read_csv('testing_errors_prob.csv')
df = df.drop(['precision', 'recall', 'TP', 'FP', 'TN', 'FN'], axis=1)
df = df.sort_values(by=['accuracy'], ascending=False)
df = df.replace({'Gaussian Nb': 'Gaussian\nNb', 'Extra Trees': 'Extra\nTrees', 'Random Forest': 'Random\nForest',
'Decision Tree': 'Decision\nTree', 'Gradient Boost': 'Gradient\nBoost', 'Linear SVC': 'Linear\nSVC',
'Ada Boost': 'Ada\nBoost', 'Bernouli Nb': 'Bernouli\nNb'})
df.plot.bar(x='model', ax=ax1, color=['#093145', '#107896', '#829356'], width=0.8)
plt.tight_layout()
# plt.xticks(rotation=45, ha="right", fontsize=6)
# plt.yticks(fontsize=6)
plt.xticks(rotation=45, ha="right", fontsize=6)
plt.yticks(fontsize=6)
plt.legend(["Accuracy", "F1", "AUC ROC"], fontsize="xx-large", prop={'size': 5})
plt.subplots_adjust(left=0.07, right=0.9, top=0.9, bottom=0.2)
plt.xlabel('')
plt.savefig('results_updateddd_{}.png'.format(size))
plt.savefig('results_updateddd_{}.pdf'.format(size))
plt.close()
The figure looks like this:
I am still not sure why, but the bug was from plt.yticks(fontsize=6). I removed it and replaced it with
ax1.tick_params(axis='both', which='major', labelsize=6)
The main issue is that subplots_adjust causes new yticks to appear when it alters the subplot layout:
yticks(fontsize=6) only targets existing ticks, so it will not affect any future ticks that show up (e.g., new ticks that appear after subplots_adjust)
tick_params(labelsize=6) sets the tick size for the whole Axes, so even when new ticks show up, they automatically inherit this tick size just by being part of the Axes
So if you want to use the yticks(fontsize=6) method, make sure to call it last:
...
plt.subplots_adjust(left=0.07, right=0.9, top=0.9, bottom=0.2)
plt.yticks(fontsize=6)
...
fontsize -> subplots_adjust
subplots_adjust -> fontsize

Increasing tick size by using axes in matplotlib

I am trying to create two axes within one figure
fig, ax = plt.subplots(2,figsize=(20,16))
This is my first figure:
ax[0].scatter(x,y, color="brown", alpha=0.4, s=200)
ax[0].plot(x,lof, color="brown", alpha=0.4)
for the first axes I want to make the x_ticks and y_ticks bigger how can I go about this?
You can use tick_params:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2,figsize=(6, 4))
ax[0].scatter([1,2,3],[1,2,3], color="brown", alpha=0.4, s=200)
ax[0].tick_params(width=2, length=4)
ax[1].tick_params(width=3, length=6)
ax[1].plot([1,2,3],[1,2,3], color="brown", alpha=0.4)
With it you can change all appearance properties of it. Here are the docs:
https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html
One way is to iterate over the major x- and y-ticks of the desired subplot (ax[0] here) and changing their font size.
Minimal representative answer
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2,figsize=(8, 4))
ax[0].scatter([1,2,3],[1,2,3], color="brown", alpha=0.4, s=200)
ax[1].plot([1,2,3],[1,2,3], color="brown", alpha=0.4)
for tick in ax[0].xaxis.get_major_ticks():
tick.label.set_fontsize(16)
for tick in ax[0].yaxis.get_major_ticks():
tick.label.set_fontsize(16)
plt.tight_layout()
plt.show()
If you don't need to differentiate between the X and Y axes, or major and minor ticks, use tick_params:
tick_size = 14
ax.tick_params(size=tick_size)
If you want to change the size of the tick labels, then you want this:
label_size = 14
ax.tick_params(labelsize=label_size)

ax.grid overwrites ticks labels when spine is in centre

When using ax.grid() and moving the spines to the middle of the plot, the grid lines go over the axes labels. Any way to stop this and move the axes labels to "front"?
EDIT: It is the ticks labels (the numbers) I'm interested in fixing, not the axis label, which can be easily moved.
EDIT: made the MWE and image match exactly
EDIT: matplotlib version 2.0.0
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = plt.gca()
ax.minorticks_on()
ax.grid(b=True, which='major', color='k', linestyle='-',alpha=1,linewidth=1)
ax.grid(b=True, which='minor', color='k', linestyle='-',alpha=1,linewidth=1)
x = np.linspace(-5,5,100)
y = np.linspace(-5,5,100)
plt.plot(x,y)
plt.yticks([-5,-4,-3,-2,-1,0,1,2,3,4,5])
ax.spines['left'].set_position(('data', 0))
plt.show()

Rotate existing axis tick labels in Matplotlib

I start with tree plots:
df = pd.DataFrame([1,20,3],[2,30,4],[3,40,5],columns=['mean','size','stat'])
fig,[ax1,ax2,ax3] = plt.subplots(1, 3, sharey=True)
ax1.barh(np.arange(len(df)),df['mean'].values, align='center')
ax2.barh(np.arange(len(df)),df['size'].values, align='center')
ax3.barh(np.arange(len(df)),df['stat'].values, align='center')
Is there a way to rotate the x axis labels on all three plots?
When you're done plotting, you can just loop over each xticklabel:
for ax in [ax1,ax2,ax3]:
for label in ax.get_xticklabels():
label.set_rotation(90)
You can do it for each ax your are creating:
ax1.xaxis.set_tick_params(rotation=90)
ax2.xaxis.set_tick_params(rotation=90)
ax3.xaxis.set_tick_params(rotation=90)
or you do it inside a for before showing the plot if you are building your axs using subplots:
for s_ax in ax:
s_ax.xaxis.set_tick_params(rotation=90)
df = pd.DataFrame([1,20,3],[2,30,4],[3,40,5],columns=['mean','size','stat'])
fig,[ax1,ax2,ax3] = plt.subplots(1, 3, sharey=True)
plt.subplot(1,3,1)
barh(np.arange(len(df)),df['mean'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")
plt.subplot(1,3,2)
barh(np.arange(len(df)),df['size'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")
plt.subplot(1,3,3)
barh(np.arange(len(df)),df['stat'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")
Should do the trick.
Here is another more generic solution: you can just use axes.flatten() which will provide you with much more flexibility when you have higher dimensions.
for i, ax in enumerate(axes.flatten()):
sns.countplot(x= cats.iloc[:, i], orient='v', ax=ax)
for label in ax.get_xticklabels():
# only rotate one subplot if necessary.
if i==3:
label.set_rotation(90)
fig.tight_layout()

How to avoid negative numbers on axis in matplotlib scatterplot

I am doing a simple scatterplot using Pythons scatterplot. But no matter how I set my axis, and no matter that I don't have any negative values I get negative values at the x-axis. How do I force the axis to start at 0?
My code:
fig, ax = plt.subplots(1)
ax.scatter(lengths,breadths, alpha=0.3, color="#e74c3c", edgecolors='none')
spines_to_remove = ['top', 'right']
for spine in spines_to_remove:
ax.spines[spine].set_visible(False)
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_view_interval(0,400)
ax.yaxis.set_view_interval(0,90)
figname = 'scatterlengthsbreadths.pdf'
fig.savefig(figname, bbox_inches='tight')
You can use ax.set_xlim(lower_limit, upper_limit) to choose your x-limits. Note that there is a similar command ax.set_ylim for the y-limits.
Note that if you're just using the pyplot interface, i.e. without using fig and ax, then the command is plt.xlim().
For example:
import matplotlib.pyplot as plt
x = [1,2,3]
y = [4,5,6]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 10)
plt.show()

Categories

Resources