How to rotate y-axis tick labels in Pandas barplot - python

For Pandas.DataFrame plot() fn, the 'rot' keyword argument rotates the x-axis ticks specifically. So how does one rotate the y-axis ticks?
There's some documentation here, which gives the anticipated syntax for the 'rot' argument for either xticks or yticks, but lacking of an example.

If you want to rotate axes ticks, it's convenient to use matplotlib feature.
After importing matplotlib as 'plt', you just have to write:
plt.xticks(rotation=specify_here_a_value)
plt.yticks(rotation=specify_here_a_value)
plt.show()
It will do the work for you. Coming to the question you asked, 'rot' keyword takes argument or rotates the axis based on the type of graph as said in the documentation:
rot : int, default None
Rotation for ticks (xticks for vertical, yticks for horizontal plots)
I think if plot is vertical, it rotates xticks and if it is horizontal it rotates yticks.
Matplotlib provides the better way as written above. I find it much more effective.

Example
axs= pd.plotting.scatter_matrix(numericData, figsize = (colNo,colNo))
for i in range(colNo):
vert = axs[i,0]
vert.yaxis.label.set_rotation(0)
vert.xaxis.label.set_ha('right')
vert.set_yticks(())
h = axs[colNo-1, i]
h.xaxis.label.set_rotation(90)
h.set_xticks(())

Related

Seaborn (violinplot) too many y-axis values

I have a couple of subplots and the data are probabilities, so should (and do) range between 0 and 1. When I plot them with a violinplot the y-axis of ax[0] extends above 1 (see pic). I know this is just because of the distribution kernel that the violinplot makes, but still it looks bad and I want the y-axes of these 2 plots to be the same. I have tried set_ylim on the left plot, but then I can't get the values (or look) to be the same as the plot on the right. Any ideas?
When creating your subplots, set the sharey parameter to True so that both plots share the same limits for the vertical axis.
[EDIT]
Since you have already tried setting sharey to True, I suggest getting the lower and upper limits ymin and ymax from the left hand side figure and passing them as arguments in set_ylim() for the right hand side figure.
1) Create your subplots:
fig, ax1 = plt.subplots(1,2, figsize = (5, 5), dpi=100)
2) Create left hand side figure here: ax[0].plot(...)
3) Get the axes limits using the get_ylim() method as detailed here: ymin, ymax = ax[0].get_ylim()
4) Create right hand side figure: ax[1].plot(...)
5) Set the axes limits of this new figure: ax[1].set_ylim(bottom=ymin, top=ymax)
I don't have subplots, but I do have probabilities, and this visual extension beyond 1.0 was frustrating to me.
If you add 'cut=0' to the sns.violinplot() call, it will truncate the kernel at the range of your data exactly.
I found the answer here:
How to better fit seaborn violinplots?

How to show the vertical scale of marginal histogram in a jointplot

In Seaborn jointplot, the marginal histograms do not show the y axis values. How can I get these values? The documentation doesn't show any arguments to change this behavior.
You're going to have to work more on the matplotlib side of things. If you just want to get the limits of the axis, you can use get_ylim. The handle for those histograms are ax_marg_x and ax_marg_y.
g = sns.jointplot(...)
g.ax_marg_x.get_ylim()
You can also make the tick labels visible using set_visible on the tick labels:
for tick in g.ax_marg_x.get_yticklabels():
tick.set_visible(True)
You can also create your own tick labels with set_yticklabels.

How do I set the size of the axes patch so that the plot labels aren't clipped (matplotlib)

I have a graph in which I've set the axis labels to scientific notation using
formatter = mpl.ticker.FormatStrFormatter('%4.2e')
axis2.yaxis.set_major_formatter(formatter)
However, the axes.patch (or whatever is the right way to express the 'canvas' extent of the plot) doesn't adjust so the tick labels and axis label are clipped:
How do I adjust the extent of the axes portion of the plot. Changing the page size (figsize = ...) doesn't do it, since that just scales the overall plot area, resulting in the same clipping problem.
You can use the method tight_layout, which will accommodate the plot in the figure available space.
Example
from pylab import *
f = figure()
f.add_subplot(111)
f.tight_layout()
show()
Hope it helps.
Cheers
Just call fig.tight_layout() (assuming you have a Figure object defined).

Change distance between boxplots in the same figure in python [duplicate]

I'm drawing the bloxplot shown below using python and matplotlib. Is there any way I can reduce the distance between the two boxplots on the X axis?
This is the code that I'm using to get the figure above:
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['ytick.direction'] = 'out'
rcParams['xtick.direction'] = 'out'
fig = plt.figure()
xlabels = ["CG", "EG"]
ax = fig.add_subplot(111)
ax.boxplot([values_cg, values_eg])
ax.set_xticks(np.arange(len(xlabels))+1)
ax.set_xticklabels(xlabels, rotation=45, ha='right')
fig.subplots_adjust(bottom=0.3)
ylabels = yticks = np.linspace(0, 20, 5)
ax.set_yticks(yticks)
ax.set_yticklabels(ylabels)
ax.tick_params(axis='x', pad=10)
ax.tick_params(axis='y', pad=10)
plt.savefig(os.path.join(output_dir, "output.pdf"))
And this is an example closer to what I'd like to get visually (although I wouldn't mind if the boxplots were even a bit closer to each other):
You can either change the aspect ratio of plot or use the widths kwarg (doc) as such:
ax.boxplot([values_cg, values_eg], widths=1)
to make the boxes wider.
Try changing the aspect ratio using
ax.set_aspect(1.5) # or some other float
The larger then number, the narrower (and taller) the plot should be:
a circle will be stretched such that the height is num times the width. aspect=1 is the same as aspect=’equal’.
http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_aspect
When your code writes:
ax.set_xticks(np.arange(len(xlabels))+1)
You're putting the first box plot on 0 and the second one on 1 (event though you change the tick labels afterwards), just like in the second, "wanted" example you gave they are set on 1,2,3.
So i think an alternative solution would be to play with the xticks position and the xlim of the plot.
for example using
ax.set_xlim(-1.5,2.5)
would place them closer.
positions : array-like, optional
Sets the positions of the boxes. The ticks and limits are automatically set to match the positions. Defaults to range(1, N+1) where N is the number of boxes to be drawn.
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.boxplot.html
This should do the job!
As #Stevie mentioned, you can use the positions kwarg (doc) to manually set the x-coordinates of the boxes:
ax.boxplot([values_cg, values_eg], positions=[1, 1.3])

Preventing xticks from overlapping yticks

How can I prevent the labels of xticks from overlapping with the labels of yticks when using hist (or other plotting commands) in matplotlib?
There are several ways.
One is to use the tight_layout method of the figure you are drawing, which will automatically try to optimize the appareance of the labels.
fig, ax = subplots(1)
ax.plot(arange(10),rand(10))
fig.tight_layout()
An other way is to modify the rcParams values for the ticks formatting:
rcParams['xtick.major.pad'] = 6
This will draw the ticks a little farter from the axes. after modifying the rcparams (this of any other, you can find the complete list on your matplotlibrc configuration file), remember to set it back to deafult with the rcdefaults function.
A third way is to tamper with the axes locator_params telling it to not draw the label in the corner:
fig, ax = subplots(1)
ax.plot(arange(10),rand(10))
ax.locator_params(prune='lower',axis='both')
the axis keywords tell the locator on which axis it should work and the prune keyword tell it to remove the lowest value of the tick
Try increasing the padding between the ticks on the labels
import matplotlib
matplotlib.rcParams['xtick.major.pad'] = 8 # defaults are 4
matplotlib.rcParams['ytick.major.pad'] = 8
same goes for [x|y]tick.minor.pad.
Also, try setting: [x|y]tick.direction to 'out'. That gives you a little more room and helps makes the ticks a little more visible -- especially on histograms with dark bars.

Categories

Resources