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?
Related
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()
I'd like to plot a series with x and y error bars, then plot a second series with x and y error bars on a second y axis all on the same subplot. Can this be done with matplotlib?
import matplotlib.pyplot as plt
plt.figure()
ax1 = plt.errorbar(voltage, dP, xerr=voltageU, yerr=dPU)
ax2 = plt.errorbar(voltage, current, xerr=voltageU, yerr=currentU)
plt.show()
Basically, I'd like to put ax2 on a second axis and have the scale on the right side.
Thanks!
twinx() is your friend for adding a secondary y-axis, e.g.:
import matplotlib.pyplot as pl
import numpy as np
pl.figure()
ax1 = pl.gca()
ax1.errorbar(np.arange(10), np.arange(10), xerr=np.random.random(10), yerr=np.random.random(10), color='g')
ax2 = ax1.twinx()
ax2.errorbar(np.arange(10), np.arange(10)+5, xerr=np.random.random(10), yerr=np.random.random(10), color='r')
There is not a lot of documentation except for:
matplotlib.pyplot.twinx(ax=None)
Make a second axes that shares the x-axis. The new axes will overlay ax (or the current axes if ax is None). The ticks for ax2 will be placed on the right, and the ax2 instance is returned.
I was struggling to share the x-axis, but thank you #Bart you saved me!
The simple solution is use twiny instead of twinx
ax1.errorbar(layers, scores_means[str(epoch)][h,:],np.array(scores_stds[str(epoch)][h,:]))
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_xlabel('depth', color='b')
ax1.tick_params('x', colors='b')
ax2 = ax1.twiny()
ax2.errorbar(hidden_dim, scores_means[str(epoch)][:,l], np.array(scores_stds[str(epoch)][:,l]))
ax2.set_xlabel('width', color='r')
ax2.tick_params('x', colors='r')
fig.tight_layout()
plt.show()
I am using matplotlib.pyplot to plot some graphs and for some reasons I can't see the lines of the axes, although I can see the xticks and yticks. Important to note that I am using python notebook, and usually I try to visualize my graphs with the function (%matplotlib inline)
Here is an example figure that I get (without the axes):
Here is the code I used to produce this figure:
fig, ax = plt.subplots(1,1, figsize=(7.5,6), sharey=False, sharex=False, edgecolor='k', frameon=True)
ax.plot(np.array(frequency_vec), before_LTP, 'b-o', label='Before');
ax.plot(np.array(frequency_vec), After_LTP, 'r-o', label='After');
plt.yticks([1,2,3,4,5,6,7,8], ['1','2','3','4','5','6','7','0'], fontsize=14)
plt.xticks(fontsize=14)
plt.rcParams['axes.edgecolor']='k'
ax.patch.set_visible(False)
ax.grid(False)
ax.set_frame_on(True)
ax.set_xlim(0, 110)
ax.set_ylim(1,(Number_of_pulses)+2)
ax.legend(loc='best', fontsize=15)
plt.xticks([12.5,25,50,75,100], ['12.5','25','50','75','100']);
So again - How can I make my axes-lines to be visible?
Thanks!
Do you have some special setting in your matplotlibrc file such as edgecolor?
import matplotlib as mpl
print mpl.rcParams['axes.edgecolor']
If it's 'w' (white) set it to 'k' (black)
If it's not edgecolor, do you have frameon = False? Try something like this:
fig, ax = subplots()
ax.plot([1,2,4],[4,5,6], 'r^-')
ax.set_frame_on(True)
I wrote that and it worked
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
Well, just write 'True' instead of 'False'.
I need to add a semi transparent skin over my matplotlib figure. I was thinking about adding a rectangle to the figure with alpha <1 and a zorder high enough so its drawn on top of everything.
I was thinking about something like that
figure.add_patch(Rectangle((0,0),1,1, alpha=0.5, zorder=1000))
But I guess rectangles are handled by Axes only. is there any turn around ?
Late answer for others who google this.
There actually is a simple way, without phantom axes, close to your original wish. The Figure object has a patches attribute, to which you can add the rectangle:
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.plot(np.cumsum(np.random.randn(100)))
fig.patches.extend([plt.Rectangle((0.25,0.5),0.25,0.25,
fill=True, color='g', alpha=0.5, zorder=1000,
transform=fig.transFigure, figure=fig)])
Gives the following picture (I'm using a non-default theme):
The transform argument makes it use figure-level coordinates, which I think is what you want.
You can use a phantom axes on top of your figure and change the patch to look as you like, try this example:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.set_zorder(1000)
ax.patch.set_alpha(0.5)
ax.patch.set_color('r')
ax2 = fig.add_subplot(111)
ax2.plot(range(10), range(10))
plt.show()
If you aren't using subplots, using gca() will work easily.
from matplotlib.patches import Rectangle
fig = plt.figure(figsize=(12,8))
plt.plot([0,100],[0,100])
plt.gca().add_patch(Rectangle((25,50),15,15,fill=True, color='g', alpha=0.5, zorder=100, figure=fig))
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)