I am drawing histograms for 4 different distributions using subplots. During the final output, I am getting tick labels for the y-axis for the fourth subplot. How shall I ensure it doesn't happen.
fig,((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2,sharex=True,sharey=True)
plt.cla()
nbins = np.arange(-10,10,1)
ax1.hist(x1,bins=nbins)
ax1.set_title('Normal Distribution')
ax1.set_ylabel('Frequency')
ax2.hist(x2,bins=nbins)
ax2.set_title('Exponential Distribution')
ax3.hist(x3,bins=nbins)
ax3.set_title('Rayleigh Distribution')
ax3.set_xlabel('Value')
ax3.set_ylabel('Frequency')
ax4.hist(x4,bins=nbins)
ax4.set_title('Random Distribution')
ax4.set_xlabel('Value')
Here is the figure I am obtaining after running the code:
After adding the following code, it removed y-tick labels for other axes too
ax4.set_yticklabels([])
Following is the graph -
This is strange, as I cannot reproduce that behavior. I don't know why ax4 would behave differently from the other axes.
But in any case, since the axes are shared, you cannot just remove the tick labels since that removes them everywhere, as you've discovered. The solution is to make them invisible on the desired ax.
plt.setp(ax4.get_xticklabels(), visible=False)
Related
I have this simple piece of code where I try to plot simple graph while limiting number of x ticks. There are hundreds of items in iters variable and if they get plotted it would just create one fat black line.
However, ax.locator_params does not work and the number of ticks aren't reduced.
I have tried setting it on plt object, but no help.
I also tried specifying x and y axes in locator_params, but no help as well.
Finally, I have tried moving ax.locator_params before and after ax.plot, but nothing seemed to help. I am completely out of ideas.
fig, ax = plt.subplots(1, 1, figsize=(20,10))
ax.locator_params(tight=True, nbins=4)
ax.plot(iters, vals)
plt.xticks(rotation=30)
plt.show()
locator_params() with nbins= is only supported for numerical axes where the tick positions are set via MaxNLocator.
To get the same effect with text ticks, the current ticks can be stored in a list (get_xticks) and then be replaced by a subset. Note that changes to ticks (and to limits) should be called after the main plot functions.
xticks = ax.get_xticks()
ax.set_xticks(xticks[::len(xticks) // 4]) # set new tick positions
ax.tick_params(axis='x', rotation=30) # set tick rotation
ax.margins(x=0) # set tight margins
I created a subplot using matplotlib.pyplot. Even as I set the tick labels to empty using:
plt.xticks([ ])
plt.yticks([ ])
How can I remove these? I am new to Python and any help on the matter is appreciated.
Your figure has many subplots in it. You need to remove the ticks in each axis object of each subplot (or at least the ones you done want to appear). This can be done like this:
import matplotlib.pyplot as plt
ax1 = plt.subplot(321) # 1st subplot in 3-by-2 grid
ax1.plot(...) # draw what you want
ax1.set_xticks([], []) # note you need two lists one for the positions and one for the labels
ax1.set_yticks([], []) # same for y ticks
ax2 = plt.subplot(321) # 2nd subplot in the same grid
# do the same thing for any subplot you want the ticks removed
If you want the whole axis (borders, ticks and labels) removed you can just do this:
ax1.axis('off')
However I'd suggest typing plt.tight_layout(). It might fix your problem without requiring you to remove the ticks.
You can use the plt.tick_params option to fine tune your plots:
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
I've set the upper x-axis manually (the conversion is 1.218x the values on the lower x-axis) and I'd like the upper minor logarithmic ticks to move up the scale by 1.218x too. Any suggestions?
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
X = np.linspace(0,10000000, 1000000)
ax1.semilogx(X, zero, label='$\mathbb{P} (X=0)$')
ax1.semilogx(X, one, label='$\mathbb{P} (X=1)$')
ax1.semilogx(X, two+more, label='$\mathbb{P} (X\geq2)$')
ax1.set_xlabel(r"Particle Concentration m$^{-3}$")
ax1.set_ylabel(r"Probability of occurrence")
ax1.legend(loc=6)
ax1.grid()
ax2.semilogx(X, one, label='one', alpha = 0)
ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks([12.18323586744639, 121.8323586744639, 1218.323586744639, 12183.23586744639, 121832.3586744639, 1218323.586744639])
ax2.set_xticklabels(['10$^1$','10$^2$','10$^3$','10$^4$','10$^5$','10$^6$'])
ax2.set_xlabel(r"Disdrometer Particle Count (min$^{-1}$)")
plt.show()
EDIT: Rewriting after your comment below.
There will be a way to move the minor ticks but actually I think your approach here is misguided. Looking close you aren't using ax2 to plot anything: you just want it as an alternative scale. You are messing with the ticks and ticklabels when as a way of faking changing the limits. It would be much easier to just change that limits (so that matplotlib can handle the ticks etc automatically).
Replace your code above with
ax2.set_xscale("log", nonposx='clip')
ax2.set_xlim(np.array(ax1.get_xlim())/1.218)
Here is the code:
plt.figure(figsize=(15,6)) # does not affect the following plot
fig, ax = plt.subplots()
ax.set_xticklabels(q9.columns.values[::-1], fontproperties=label_font, fontsize=14)
sns.barplot(q9.columns.values, q9.iloc[[1]].get_values()[0], palette="GnBu_d", ax=ax)
I had to set the font in this case, so I need the ax object. The final plot is really small, definitely not (15,6). I think by setting ax=ax changed the size of the plot to its default size.
Any idea on how to change the size of the figure in this case?
You are making two figures, with the call to plt.figure and plt.subplots. You are setting the size only on the first figure, but you are using the second figure to draw your barplot.
I have two stacked subplots which share the x axis, for both subplots visibility of ticks is set to false because I don't want to see tick labels. after having plotted both subplots, I would like to put some extra ticks on x-asis, only for second subplot, but they don't have to became the main ticks.
I mean, doing this:
#xticks = list of x points
#xlabs = list of labels
#secondplot.set_xticks(xticks)
#secondplot.set_xticklabels(xlabs)
will change the first sublplot grid according to these new ticks as if they became the new major ticks. is there a way to label just some x-axis point in second subplot without affecting the whole plots area? thank you
I know im late to the party but I faced a similar problem and want to share my solution, in case anyone else needs help.
You can use matplotlib.axes.Axes.tick_params to control the style of both major and minor ticks of the axes. Setting the tick lengths of the first subplot to 0 should do the trick:
ax.tick_params(axis="x", which="both", length=0.)
axis ("x", "y" or "both") selects the axes, on which the setting has an effect, which ("major", "minor" or "both") chooses the tick type.
Of course you can then also set major and minor ticks with ax.set_xticks(ticks, minor=False). A full example:
import matplotlib.pyplot as plt
fig, axarr = plt.subplots(2, 1, sharex="col")
axarr[0].plot(range(11))
axarr[1].plot(range(11)[::-1])
axarr[0].tick_params(axis="x", which="both", length=0.)
axarr[1].set_xticks(range(0, 11, 3))
axarr[1].set_xticks(range(0, 11), minor=True)
plt.show()
which yields: https://i.stack.imgur.com/oc7y0.png
This works for removing the tick labels from a single axis when using sharex, but I don't see a solution to also remove the ticks..
import matplotlib.pylab as pl
pl.figure()
ax1=pl.subplot(211)
ax1.plot([0,10],[0,10])
ax2=pl.subplot(212, sharex=ax1)
ax2.plot([0,10],[10,0])
pl.setp(ax1.get_xticklabels(), visible=False)