This question already has answers here:
Remove xticks in a matplotlib plot?
(11 answers)
Closed 8 years ago.
I'm using subplots in matplotlib. Since all of my subplots have the same x-axis, I only want to label the x-axis on my bottom plot. How can I remove xtics from just one axis?
As pointed out here, the following works!
plt.tick_params(\
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
labelbottom='off') # labels along the bottom edge are off
Dan, if you've set up your plots in an OOP way using
import matplotlib.pyplot as plt
fig, ax_arr = subplots(3, 1, sharex=True)
then it should be easy to hide the x-axis labels using something like
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
# or
plt.setp([a.get_xticklabels() for a in ax_arr[:-1]], visible=False)
But check out this link and some of the further down examples will prove useful.
Edit:
If you can't use plt.subplots(), I'm still assuming you can do
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot(x1, y1)
ax2.plot(x2, y2)
plt.setp(ax1.get_xticklabels(), visible=False)
If you have more than 2 subplots, such as
ax1 = fig.add_subplot(N11)
ax2 = fig.add_subplot(N12)
...
axN = fig.add_subplot(N1N)
plt.setp([a.get_xticklabels() for a in (ax1, ..., axN-1)], visible=False)
Related
I have been using this piece of code for drawing 2 subplots on the same figure. I tried many things for adding space between bars of barh in matplotlib so the labels of y-axis would be readable but I could not fix it:
plt.figure(figsize=(30, 120))
fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].barh(names, gaps, align='edge', color='green',height=1)
axes[1].barh(names, mems, align='edge', color='blue',height=1)
axes[0].invert_xaxis()
axes[0].set_yticklabels(names, fontsize=5)
axes[0].yaxis.tick_right()
for ax in axes.flat:
ax.margins(0.01)
ax.grid(True)
fig.tight_layout()
fig.subplots_adjust(wspace=0.37)
My current figure looks like this:
my current figure
Do you know how I can make the ylabels readable?
This question already has answers here:
How to move tick labels off left spine
(2 answers)
Closed 3 years ago.
I am attempting to plot a distribution which is centred around zero, and as such I want to show the y-axis spine at 0, but I want to keep the tick labels themselves to the left of the graph (i.e. outside the plot area). I thought this might be achievable through tick_params, but the labelleft option seems to keep the labels in the centre. A short example is as follows:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1)
vals = np.random.normal(loc=0, scale=10, size=300)
bins = range(int(min(vals)), int(max(vals))+1)
fig, ax = plt.subplots(figsize=(15,5))
ax.hist(vals, bins=bins)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid(axis='y', which='major', alpha=0.5)
plt.show()
This gives you:
I would like the labels to be at the left end of the gridlines, rather than the centre of the plot.
Probably not the best solution, but you can set left spines invisible and draw a straight line at 0:
ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.plot((0,0), (0,ax.get_ylim()[-1]),color='k',linewidth=1)
ax.grid(axis='y', which='major', alpha=0.5)
plt.show()
Output:
On possibility is to instruct the tick labels to use the "Axes coordinates" for their x position, and the "Data coordinates" for their y position. This implies changing their tranform property.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.transforms as transforms
np.random.seed(1)
vals = np.random.normal(loc=0, scale=10, size=300)
bins = range(int(min(vals)), int(max(vals))+1)
fig, ax = plt.subplots()
ax.hist(vals, bins=bins)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid(axis='y', which='major', alpha=0.5)
trans = transforms.blended_transform_factory(ax.transAxes,ax.transData)
plt.setp(ax.get_yticklabels(), 'transform', trans)
plt.show()
This question already has answers here:
Show tick labels when sharing an axis in matplotlib
(3 answers)
Closed 4 years ago.
When use sharex or sharey in subplots, the tick labels would disappeared, how to turn them back?
Here is an example just copied from the official website:
fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)
axs[0, 0].plot(x)
plt.show()
And we will see:
As we can see, the top-right plot doesn't have any tick labels, and others also lack some labels because of the axis was shared.
I think I should use something like plt.setp(ax.get_xticklabels(), visible=True), but it doesn't work.
You can use the tick_params() to design the plot:
f, ax = plt.subplots(2, 2, sharex=True, sharey=True)
for a in f.axes:
a.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=True,
top=False,
labelbottom=True) # labels along the bottom edge are on
plt.show()
This question already has answers here:
matplotlib - No xlabel and xticks for twinx axes in subploted figures
(2 answers)
Closed 5 years ago.
This happens when I try to plot a line and an area on the same subplot. I found the my x-ticks disappear after I call ay=ax.twinx() and plot on ay.
Here's my code that causes this error.
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=[12,12])
data=pd.DataFrame([[1,2,3],[2,3,4],[3,2,4]])
ix = np.unravel_index(0, axes.shape)
ax=axes[ix]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
ax2=ax.twinx()
data.plot(ax=ax,color=['navy','red'])
ax2.plot(y.values, linewidth=2.0)
As you can see, the x-ticks disappear.
However, if you continue plotting, you can find the last subplot isn't affected.
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=[12,12])
data=pd.DataFrame([[1,2,3],[2,3,4],[3,2,4]])
ix = np.unravel_index(0, axes.shape)
ax=axes[ix]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
ax2=ax.twinx()
data.plot(ax=ax,color=['navy','red'])
ax2.plot(y.values, linewidth=2.0)
ix = np.unravel_index(1, axes.shape)
ax=axes[ix]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
ax2=ax.twinx()
data.plot(ax=ax,color=['navy','red'])
ax2.plot(y.values, linewidth=2.0)
There are two options. One is based on the answer to this question: matplotlib - pandas - No xlabel and xticks for twinx axes in subploted figures
which is to reverse the order of plotting. First plot to the two subplots, then create the twin axes for both.
import matplotlib.pyplot as plt
import pandas as pd
fig, axes = plt.subplots(nrows=2, ncols=1)
data=pd.DataFrame([[1,2,3],[2,3,4],[3,2,4]])
ax=axes[0]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
data.plot(ax=ax)
ax3=axes[1]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
data.plot(ax=ax3)
ax2=ax.twinx()
ax2.plot(y.values)
ax4=ax3.twinx()
ax4.plot(y.values)
plt.show()
Now sometimes the above may not be an option, so the second possible solution would be to set the ticks visible again after the complete plot has been generated.
[t.set_visible(True) for t in ax.get_xticklabels()]
Complete example:
import matplotlib.pyplot as plt
import pandas as pd
fig, axes = plt.subplots(nrows=2, ncols=1)
data=pd.DataFrame([[1,2,3],[2,3,4],[3,2,4]])
ax=axes[0]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
ax2=ax.twinx()
data.plot(ax=ax)
ax2.plot(y.values)
ax3=axes[1]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
ax4=ax3.twinx()
data.plot(ax=ax3)
ax4.plot(y.values)
[t.set_visible(True) for t in ax.get_xticklabels()]
plt.show()
How do I show a plot with twin axes such that the aspect of the top and right axes are 'equal'. For example, the following code will produce a square plot
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.plot([0,1],[0,1])
But this changes as soon as you use the twinx function.
ax2 = ax.twinx()
ax2.set_ylim([0,2])
ax3 = ax.twiny()
ax3.set_xlim([0,2])
Using set_aspect('equal') on ax2 and ax3 seems to force it the the aspect of ax, but set_aspect(0.5) doesn't seem to change anything either.
Put simply, I would like the plot to be square, the bottom and left axes to run from 0 to 1 and the top and right axes to run from 0 to 2.
Can you set the aspect between two twined axes? I've tried stacking the axes:
ax3 = ax2.twiny()
ax3.set_aspect('equal')
I've also tried using the adjustable keyword in set_aspect:
ax.set_aspect('equal', adjustable:'box-forced')
The closest I can get is:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_aspect('equal', adjustable='box-forced')
ax.plot([0,1],[0,1])
ax2=ax.twinx()
ax3 = ax2.twiny()
ax3.set_aspect(1, adjustable='box-forced')
ax2.set_ylim([0,2])
ax3.set_xlim([0,2])
ax.set_xlim([0,1])
ax.set_ylim([0,1])
Which produces:
I would like to remove the extra space to the right and left of the plot
It seems overly complicated to use two different twin axes to get two independent set of axes. If the aim is to create one square plot with one axis on each side of the plot, you may use two axes, both at the same position but with different scales. Both can then be set to have equal aspect ratios.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.plot([0,1],[0,1])
ax2 = fig.add_axes(ax.get_position())
ax2.set_facecolor("None")
ax2.set_aspect('equal')
ax2.plot([2,0],[0,2], color="red")
ax2.tick_params(bottom=0, top=1, left=0, right=1,
labelbottom=0, labeltop=1, labelleft=0, labelright=1)
plt.show()