Removing axis ticks from one subplot - python

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)

Related

How to have the axis ticks in both top and bottom, left and right of a heatmap

I am trying to draw a big heatmap with sns.heatmap function. However, since the map is too big, it's a little hard to find the xtick label or ytick label with corresponding rows and columns. Can I add the xtick and xlabels also on the top and ytick and ylabels also on the right??
I have tried many different ways. But they all didn't work.
The usual way would be via tick_params, which has the labelrotation parameter, and accepts rotation:
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)
import seaborn as sns
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
ax.tick_params(right=True, top=True, labelright=True, labeltop=True, labelrotation=0)
plt.show()
Without labelrotation=0 or rotation=0
Axis ticks for all sides can be placed using tick_params from matplotlib
#Get sample correlation data to plot something. 'data' is a dataframe
corr=data.corr()
#Create Heatmap
axr = sns.heatmap(corr,cmap="coolwarm", annot=True, linewidths=.5,cbar=False)
#Set all sides
axr.tick_params(right=True, top=True, labelright=True, labeltop=True,rotation=0)
#Rotate X ticks
plt.xticks(rotation='vertical')

Histogram at specific coordinates inside axes

What I want to achieve with Python 3.6 is something like this :
Obviously made in paint and missing some ticks on the xAxis. Is something like this possible? Essentially, can I control exactly where to plot a histogram (and with what orientation)?
I specifically want them to be on the same axes just like the figure above and not on separate axes or subplots.
fig = plt.figure()
ax2Handler = fig.gca()
ax2Handler.scatter(np.array(np.arange(0,len(xData),1)), xData)
ax2Handler.hist(xData,bins=60,orientation='horizontal',normed=True)
This and other approaches (of inverting the axes) gave me no results. xData is loaded from a panda dataframe.
# This also doesn't work as intended
fig = plt.figure()
axHistHandler = fig.gca()
axScatterHandler = fig.gca()
axHistHandler.invert_xaxis()
axHistHandler.hist(xData,orientation='horizontal')
axScatterHandler.scatter(np.array(np.arange(0,len(xData),1)), xData)
A. using two axes
There is simply no reason not to use two different axes. The plot from the question can easily be reproduced with two different axes:
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("ggplot")
xData = np.random.rand(1000)
fig,(ax,ax2)= plt.subplots(ncols=2, sharey=True)
fig.subplots_adjust(wspace=0)
ax2.scatter(np.linspace(0,1,len(xData)), xData, s=9)
ax.hist(xData,bins=60,orientation='horizontal',normed=True)
ax.invert_xaxis()
ax.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax2.tick_params(axis="y", left=0)
plt.show()
B. using a single axes
Just for the sake of answering the question: In order to plot both in the same axes, one can shift the bars by their length towards the left, effectively giving a mirrored histogram.
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("ggplot")
xData = np.random.rand(1000)
fig,ax= plt.subplots(ncols=1)
fig.subplots_adjust(wspace=0)
ax.scatter(np.linspace(0,1,len(xData)), xData, s=9)
xlim1 = ax.get_xlim()
_,__,bars = ax.hist(xData,bins=60,orientation='horizontal',normed=True)
for bar in bars:
bar.set_x(-bar.get_width())
xlim2 = ax.get_xlim()
ax.set_xlim(-xlim2[1],xlim1[1])
plt.show()
You might be interested in seaborn jointplots:
# Import and fake data
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randn(2,1000)
# actual plot
jg = sns.jointplot(data[0], data[1], marginal_kws={"bins":100})
jg.ax_marg_x.set_visible(False) # remove the top axis
plt.subplots_adjust(top=1.15) # fill the empty space
produces this:
See more examples of bivariate distribution representations, available in Seaborn.

Changing matplotlib subplot size/position after axes creation

Is it possible to set the size/position of a matplotlib subplot after the axes are created? I know that I can do:
import matplotlib.pyplot as plt
ax = plt.subplot(111)
ax.change_geometry(3,1,1)
to put the axes on the top row of three. But I want the axes to span the first two rows. I have tried this:
import matplotlib.gridspec as gridspec
ax = plt.subplot(111)
gs = gridspec.GridSpec(3,1)
ax.set_subplotspec(gs[0:2])
but the axes still fill the whole window.
Update for clarity
I want to change the position of an existing axes instance rather than set it when it is created. This is because the extent of the axes will be modified each time I add data (plotting data on a map using cartopy). The map may turn out tall and narrow, or short and wide (or something in between). So the decision on the grid layout will happen after the plotting function.
Thanks to Molly pointing me in the right direction, I have a solution:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
ax = fig.add_subplot(111)
gs = gridspec.GridSpec(3,1)
ax.set_position(gs[0:2].get_position(fig))
ax.set_subplotspec(gs[0:2]) # only necessary if using tight_layout()
fig.add_subplot(gs[2])
fig.tight_layout() # not strictly part of the question
plt.show()
You can create a figure with one subplot that spans two rows and one subplot that spans one row using the rowspan argument to subplot2grid:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = plt.subplot2grid((3,1), (0,0), rowspan=2)
ax2 = plt.subplot2grid((3,1), (2,0))
plt.show()
If you want to change the subplot size and position after it's been created you can use the set_position method.
ax1.set_position([0.1,0.1, 0.5, 0.5])
Bu you don't need this to create the figure you described.
You can avoid ax.set_position() by using fig.tight_layout() instead which recalculates the new gridspec:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# create the first axes without knowing of further subplot creation
fig, ax = plt.subplots()
ax.plot(range(5), 'o-')
# now update the existing gridspec ...
gs = gridspec.GridSpec(3, 1)
ax.set_subplotspec(gs[0:2])
# ... and recalculate the positions
fig.tight_layout()
# add a new subplot
fig.add_subplot(gs[2])
fig.tight_layout()
plt.show()

Matplotlib - imshow twiny() problems

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.

how to turn on minor ticks only on y axis matplotlib

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.

Categories