Color all tick labels in scientific notation - python

I want to color the tick labels of my left vertical axis. However, the following code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,5,10],[1,5,10])
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlim([1e0,1e1])
ax.set_ylim([1e0,1e1])
ax.yaxis.label.set_color('b')
ax.spines['left'].set_edgecolor('b')
ax.tick_params(axis='y', colors='b')
plt.savefig('test.png')
plt.show()
fails to color all lables:

Use
ax.tick_params(axis='y', colors='b', which='both')
where both corresponds to the major as well as the minor ticks.
Output

Related

Set the number of minor ticks in matplotlib colorbar

I am able to set the number of major ticks of the colorbar using the following code borrowed from here:
cbar = plt.colorbar()
cbar.ax.locator_params(nbins=5)
Is there a similar way of setting the minor ticks of the colorbar?
You can use the AutoMinorLocator to set the number of minor ticks (note that when setting n=4, one of the major ticks is counted as 1). Here is an example:
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, ScalarFormatter
import numpy as np
data = np.random.rand(10, 10)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))
img1 = ax1.imshow(data, cmap='inferno', aspect='auto', vmin=0, vmax=1)
cbar1 = plt.colorbar(img1, ax=ax1)
ax1.set_title('default colorbar ticks')
img2 = ax2.imshow(data, cmap='inferno', aspect='auto', vmin=0, vmax=1)
cbar2 = plt.colorbar(img2, ax=ax2)
# 3 major ticks
cbar2.ax.locator_params(nbins=3)
# 4 minor ticks, including one major, so 3 minor ticks visible
cbar2.ax.yaxis.set_minor_locator(AutoMinorLocator(n=4))
# show minor tick labels
cbar2.ax.yaxis.set_minor_formatter(ScalarFormatter())
# change the color to better distinguish them
cbar2.ax.tick_params(which='minor', color='blue', labelcolor='crimson')
ax2.set_title('3 major, 4 minor colorbar ticks')
plt.tight_layout()
plt.show()

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
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)
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:

Plot grid lines but hide axes

Seems like a simple request but haven't had any luck so far. I thought it would be as simple as
import matplotlib.pyplot as plt
fig = plt.plot([1,2], [1,2])
plt.grid(True)
plt.axis('off')
but that will get rid of the grid as well.
To be clear, I do not want the labels, ticks or thick axis lines, just the grid.
Try:
fig, ax = plt.subplots(1,1)
ax.plot([1,2], [1,2])
plt.grid(True)
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_frame_on(False)
ax.tick_params(tick1On=False)
plt.show()

Hide the short lines of axis tickers in plt.subplots [duplicate]

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:

How to move specific x-axis (minor) tick labels to the top of a figure in matplotlib?

I want to keep the major tick labels, that matplotlib has automatically generated, in their default position under the figure. However, I myself added some minor ticks (with vertical lines) at specific x values, but their labels don't fit between the default major ticks. How can I move these labels to the top of the figure?
My code for reference:
meta = comparisons['meta']
lagsAnycast = np.array(meta['lagsAnycast'])
lagsPenultimate = np.array(meta['lagsPenultimate'])
avgLagAnycast = meta['avgLagAnycast']
avgLagPenultimate = meta['avgLagPenultimate']
plt.step(lagsAnycast, (np.arange(lagsAnycast.size) + 1)/lagsAnycast.size, color='k', label='to anycast IPs', linewidth=1.5)
plt.step(lagsPenultimate, (np.arange(lagsPenultimate.size) + 1)/lagsPenultimate.size, color='k', label='to penultimate IPs', linewidth=1)
plt.axvline(round(avgLagAnycast,1), ls="dashed", color="k", label="average lag to anycast IPs", linewidth=1.5)
plt.axvline(round(avgLagPenultimate,1), ls="dashed", label="average lag to penultimate IPs", color="k", linewidth=1)
plt.axis([-0.34,60,0.7,1])
plt.xlabel("Lag (ms)")
plt.ylabel("CDF")
existingTicks = (plt.xticks())[0][1:].tolist()
plt.gca().xaxis.grid(True, which='major')
plt.gca().xaxis.grid(False, which='minor')
plt.gca().tick_params(axis="x", which="minor", direction="out", top=True)
plt.gca().set_xticks([round(avgLagAnycast,1), round(avgLagPenultimate,1)], minor=True)
plt.legend(loc='right', fontsize=10)
plt.grid(True, ls="dotted")
majorFormatter = FormatStrFormatter('%g')
plt.gca().xaxis.set_major_formatter(majorFormatter)
plt.savefig(os.path.join(os.getcwd(), "datasets/plots/CDF1.png"))
You can use Locators and Formatters to set the ticks and ticklabels and turn them on or off using tick_params:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = np.linspace(-3,3)
plt.plot(x, np.sin(x))
ticks = [-np.pi/2,np.pi/2.]
labels = [r"$-\frac{\pi}{2}$",r"$\frac{\pi}{2}$"]
ax = plt.gca()
ax.xaxis.set_minor_locator(ticker.FixedLocator(ticks))
ax.xaxis.set_minor_formatter(ticker.FixedFormatter(labels))
# Set visibility of ticks & tick labels
ax.tick_params(axis="x", which="minor", direction="out",
top=True, labeltop=True, bottom=False, labelbottom=False)
plt.show()

Categories