How can I turn the minor ticks only on y axis on a linear vs linear plot?
When I use the function minor_ticks_on to turn minor ticks on, they appear on both x and y axis.
Nevermind, I figured it out.
ax.tick_params(axis='x', which='minor', bottom=False)
Here's another way I found in the matplotlib documentation:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
a = np.arange(100)
ml = MultipleLocator(5)
plt.plot(a)
plt.axes().yaxis.set_minor_locator(ml)
plt.show()
This will place minor ticks on only the y-axis, since minor ticks are off by default.
To clarify the procedure of #emad's answer, the steps to show minor ticks at default locations are:
Turn on minor ticks for an axes object, so locations are initialized as Matplotlib sees fit.
Turn off minor ticks that are not desired.
A minimal example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.plot([1,2])
# Currently, there are no minor ticks,
# so trying to make them visible would have no effect
ax.yaxis.get_ticklocs(minor=True) # []
# Initialize minor ticks
ax.minorticks_on()
# Now minor ticks exist and are turned on for both axes
# Turn off x-axis minor ticks
ax.xaxis.set_tick_params(which='minor', bottom=False)
Alternative Method
Alternatively, we can get minor ticks at default locations using AutoMinorLocator:
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig, ax = plt.subplots()
plt.plot([1,2])
ax.yaxis.set_minor_locator(tck.AutoMinorLocator())
Result
Either way, the resulting plot has minor ticks on the y-axis only.
To set minor ticks at custom locations:
ax.set_xticks([0, 10, 20, 30], minor=True)
Also, if you only want minor ticks on the actual y-axis, rather than on both the left and right-hand sides of the graph, you can follow the plt.axes().yaxis.set_minor_locator(ml) with plt.axes().yaxis.set_tick_params(which='minor', right = 'off'), like so:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
a = np.arange(100)
ml = MultipleLocator(5)
plt.plot(a)
plt.axes().yaxis.set_minor_locator(ml)
plt.axes().yaxis.set_tick_params(which='minor', right = 'off')
plt.show()
The following snippets should help:
from matplotlib.ticker import MultipleLocator
ax.xaxis.set_minor_locator(MultipleLocator(#))
ax.yaxis.set_minor_locator(MultipleLocator(#))
# refers to the desired interval between minor ticks.
Related
I want to draw multiple bar plots with the same y-scale, and so I need the y-scale to be consistent.
For this, I tried using ylim() after yscale()
plt.yscale("log")
plt.ylim(top=2000)
plt.show()
However, python keeps autoscaling the intermittent values depending on my data.
Is there a way to fix this?
overlayed graphs
import numpy as np
import matplotlib.pyplot as plt
xaxis = np.arange(10)
yaxis = np.random.rand(10)*100
fig = plt.subplots(figsize =(10, 7))
plt.bar(xaxis, yaxis, width=0.8, align='center', color='y')
# show graph
plt.yscale("log")
plt.ylim(top=2000)
plt.show()
You can set the y-axis tick labels manually. See yticks for an example. In your case, you will have to do this for each plot to have consistent axes.
I have a log-log plot where minor ticklines shows only in x axis not in y axis. Because my y-axis major ticks are not spaced like x-axis.
plot
Here is my code,
import numpy as np
import matplotlib.pyplot as plt
z = np.loadtxt("msd_profile2.out",delimiter=' ',skiprows=200005)[:, 5]
y= np.loadtxt("msd_profile2.out",delimiter=' ',skiprows=200005)[:, 4]
x=np.loadtxt("msd_profile2.out",delimiter=' ',skiprows=200005)[:, 3]
time =np.loadtxt("msd_profile2.out",delimiter=' ',skiprows=200005)[:, 2]
xy= (np.sqrt(x**2+y**2))
plt.rc('font', size=18,family='serif')
plt.rc('xtick', labelsize='x-small')
plt.rc('ytick', labelsize='x-small')
fig, ax = plt.subplots()
ax.plot(time, z,label="Z")
ax.plot(time, xy,label="XY")
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel('Time')
ax.set_ylabel('MSD')
ax.legend()
plt.savefig('H:/figure/msd_ar12.png', dpi=600)
plt.show()
How can I add customize tick spacing in yaxis? I think it suppose to be done by default.
read the matplotlib documentation. It appear minor ticks are turned off by default.
You may need to import from matplotlib.ticker to get the MultipleLocator to specify the frequency of your ticks.
I'm having trouble removing axis labels from only one subplot. Everything I try removes both. My goal is to keep ticks on the left plot, but remove them on the right. Here's what I've tried.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
#some data.
x = np.arange(1,11)
fig = plt.figure(1)
grid = gridspec.GridSpec(1, 2)
grid.update(hspace=0)
plt0 = plt.subplot(grid[0,0])
plt.plot(x,x)
plt1 = plt.subplot(grid[0,1], sharey =plt0)
#The line below removes ticks from both subplots.
plt1.set_yticks([])
plt.plot(x,2*x)
Any help would be greatly appreciated.
You can use labelleft=False to turn off the tick labels and length=0 to hide the tick marks.
plt1.tick_params(labelleft=False, length=0)
plt.plot(x, 2*x)
I have several histograms that I need to plot with seaborn / facetgrid. They each have their own different x/y axis scales. I need to control the space between the ticks, so as to make it readable (right now they are all overlapping with each other). It won't help to force set the ticks, as each histogram has it's own scale. Here is my current code:
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set(style="ticks")
g = sns.FacetGrid(test, col="someCol", sharex=False, sharey=False)
g.map(plt.hist, "someVal")
And this is what my histograms look like so far:
You can rotate the ticks using this command :
ax.tick_params(axis='x', rotation = 90, labelsize = 20)
I am trying to have two inter-depedent x-axis in a matplotlib imshow() plot. I have bottom x-axis as the radius squared and I want the top as just the radius. I have tried so far:
ax8 = ax7.twiny()
ax8._sharex = ax7
fmtr = FuncFormatter(lambda x,pos: np.sqrt(x) )
ax8.xaxis.set_major_formatter(fmtr)
ax8.set_xlabel("Radius [m]")
where ax7 is the y-axis and the bottom x-axis (or radius squared). Instead of getting the sqrt (x_bottom) as the ticks at the top I just get a range from 0 to 1. How can I fix this?
Thanks a lot in advance.
You're misunderstanding what twiny does. It makes a completely independent x-axis with a shared y-axis.
What you want to do is have a different formatter with a linked axis (i.e. sharing the axis limits but nothing else).
The simple way to do this is to manually set the axis limits for the twinned axis:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
fig, ax1 = plt.subplots()
ax1.plot(range(10))
ax2 = ax1.twiny()
formatter = FuncFormatter(lambda x, pos: '{:0.2f}'.format(np.sqrt(x)))
ax2.xaxis.set_major_formatter(formatter)
ax2.set_xlim(ax1.get_xlim())
plt.show()
However, as soon as you zoom or interact with the plot, you'll notice that the axes are unlinked.
You could add an axes in the same position with both shared x and y axes, but then the tick formatters are shared, as well.
Therefore, the easiest way to do this is using a parasite axes.
As a quick example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
fig = plt.figure()
ax1 = SubplotHost(fig, 1,1,1)
fig.add_subplot(ax1)
ax2 = ax1.twin()
ax1.plot(range(10))
formatter = FuncFormatter(lambda x, pos: '{:0.2f}'.format(np.sqrt(x)))
ax2.xaxis.set_major_formatter(formatter)
plt.show()
Both this and the previous plot will look identical at first. The difference will become apparent when you interact (e.g. zoom/pan) with the plot.