removing ticklabels python - pandas

I am plotting a multipanel figure in python using a pandas dataframe. I have used the shorter version:
df1_5.plot(subplots=True, sharex=True);
which removes xtick labels on all but the bottom figure in a 5 row by 1 column figure format.
However in order to customize the plots, I was more explicit about how I plotted and used the following code:
fig, axes = plt.subplots(nrows=5, ncols=1, figsize=(8, 5))
df11_15['V11'].plot(ax=axes[0], ylim=(0, 7)); axes[0].set_title('V1')
df11_15['V12'].plot(ax=axes[1], ylim=(0, 7)); axes[1].set_title('V12')
df11_15['V13'].plot(ax=axes[2], ylim=(-0.5, 1.0)); axes[2].set_title('V13')
df11_15['V14'].plot(ax=axes[3], ylim=(-0.5,0.5)); axes[3].set_title('V14')
df11_15['V15'].plot(ax=axes[4], ylim=(-0.5, 0.5)); axes[4].set_title('V15')
I would like to remove the xticklabels from the upper four plots. Can you tell me how to do this?
I tried:
axes[3].set_axisticklabels()
but was told there was no attribute error named this.

Try this
for label in ax[3].get_xticklabels():
label.set_visible(False)
For completeness I will also provide example on how this works in a loop
# generate 2x4 matrix of subplots
fig, axs = plt.subplots(nrows=4, ncols=2)
for i,ax in enumerate(fig.axes):
# fill histograms with random numbers
ax.hist(np.random.normal(size = 100), bins=20)
# set the same xlim so that making labels invisible makes sense
ax.set_xlim([-4,4])
# make labels invisible only if "ax" is not in the last row
if not ax.is_last_row():
for label in ax.get_xticklabels():
label.set_visible(False)

Related

How to draw a grid in a bar-plot created with plt.vlines()

I want to create a bar-plot in python. I want this plot to be beautiful though and I don't like the looks of python's axes.bar() function. Therefore, I have decided to use plt.vlines(). The challenge here is that my x-data is a list that contains strings and not numerical data. When I plot my graph, the spacing between the two columns (in my example column 2 = 0) is pretty big:
Furthermore, I want a grid. However, I would like to have minor grid lines as well. I know how to get all of this if my data was numerical. But since my x-data contains strings, I don't know how to set x_max. Any suggestions?
Internally, the positions of the labels are numbered 0,1,... So setting the x-limits a bit before 0 and after the last, shows them more centered.
Usually, bars are drawn with their 'feet' on the ground, which can be set via plt.ylim(0, ...). Minor ticks can be positioned for example at multiples of 0.2. Setting the length of the ticks to zero lets the position count for the grid, but suppresses the tick mark.
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np
labels = ['Test 1', 'Test 2']
values = [1, 0.7]
fig, ax = plt.subplots()
plt.vlines(labels, 0, values, colors='dodgerblue', alpha=.4, lw=7)
plt.xlim(-0.5, len(labels) - 0.5) # add some padding left and right of the bars
plt.ylim(0, 1.1) # bars usually have their 0 at the bottom
ax.xaxis.set_minor_locator(MultipleLocator(.2))
plt.tick_params(axis='x', which='both', length=0) # ticks not shown, but position serves for gridlines
plt.grid(axis='both', which='both', ls=':') # optionally set the linestyle of the grid
plt.show()

How do I remove the axis tick marks on seaborn heatmap

I have a seaborn heatmap but i need to remove the axis tick marks that show as dashes. I want the tick labels but just need to remove the dash (-) at each tick on both axes. My current code is:
sns.heatmap(df, annot=True, fmt='.2f', center=0)
I tried despine and that didnt work.
#ImportanceOfBeingEarnest had a nice answer in the comments that I wanted to add as an answer (in case the comment gets deleted).
For a heatmap:
ax = sns.heatmap(df, annot=True, fmt='.2f', center=0)
ax.tick_params(left=False, bottom=False) ## other options are right and top
If this were instead a clustermap (like here How to remove x and y axis labels in a clustermap?), you'd have an extra call:
g = sns.clustermap(...)
g.ax_heatmap.tick_params(left=False, bottom=False)
And for anyone who wanders in here looking for the related task of removing tick labels, see this answer (https://stackoverflow.com/a/26428792/3407933).
ax = sns.heatmap(df, annot=True, fmt='.2f', center=0)
ax.tick_params(axis='both', which='both', length=0)
ax is a matplotlib.axes object. All axes parameters can be changed in this object, and here's an example from the matplotlib tutorial on how to change tick parameters. both selects both x and y axis, and then their length is changed to 0, so that the ticks are not visible anymore.

Matplotlib Subplots -- Get Rid of Tick Labels Altogether

Is there a way to get rid of tick labels altogether when creating an array of subplots in Matplotlib? I am currently needing to specify each plot based on the row and column of a larger data set to which the plot corresponds. I've attempted to use the ax.set_xticks([]) and the similar y-axis command, to no avail.
I recognize that it's probably an unusual request to want to make a plot with no axis data whatsoever, but that's what I need. And I need it to automatically apply to all of the subplots in the array.
You have the right method. Maybe you are not applying the set_xticks to the correct axes.
An example:
import matplotlib.pyplot as plt
import numpy as np
ncols = 5
nrows = 3
# create the plots
fig = plt.figure()
axes = [ fig.add_subplot(nrows, ncols, r * ncols + c) for r in range(0, nrows) for c in range(0, ncols) ]
# add some data
for ax in axes:
ax.plot(np.random.random(10), np.random.random(10), '.')
# remove the x and y ticks
for ax in axes:
ax.set_xticks([])
ax.set_yticks([])
This gives:
Note that each axis instance is stored in a list (axes) and then they can be easily manipulated. As usual, there are several ways of doing this, this is just an example.
Even more concise than #DrV 's answer, remixing #mwaskom's comment, a complete and total one-liner to get rid of all axes in all subplots:
# do some plotting...
plt.subplot(121),plt.imshow(image1)
plt.subplot(122),plt.imshow(image2)
# ....
# one liner to remove *all axes in all subplots*
plt.setp(plt.gcf().get_axes(), xticks=[], yticks=[]);
Note: this must be called before any calls to plt.show()
The commands are the same for subplots
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot([1,2])
ax1.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)
)
plt.draw()
You can get rid of the default subplot x and y ticks with simply running the following codes:
fig, ax = plt.subplots()
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
for i in range(3):
ax = fig.add_subplot(3, 1, i+1)
...
Just by adding the 2 aforementioned lines just after fig, ax = plt.subplots() you can remove the default ticks.
One can remove the xticks or yticks by
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
If you want to turn off also the spines, so having no axis at all, you can use:
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
And if you want to turn everything off at once, use:
ax.axis("off")

matplotlib: adding padding/offset to polar plots tick labels

Is there a way to increase the padding/offset of the polar plot tick labels (theta)?
import matplotlib
import numpy as np
from matplotlib.pyplot import figure, show, grid
# make a square figure
fig = figure(figsize=(2, 2))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c')
ax.set_yticklabels([])
r = np.arange(0, 3.0, 0.01)
theta = 2*np.pi*r
ax.plot(theta, r, color='#ee8d18', lw=3)
ax.set_rmax(2.0)
show()
I'd like to have theta tick labels further away from the polar plot so they don't overlap.
First of all; seeing as how you have specified the figsize to be (2,2) and having the ax occupy 80 % of both the width and height, you have very little space left over to pad the ticklabels. This could cause the ticklabels to be "cut off" at the figure's egdes. This can easily be "fixed" by either
Specifying bigger figsize
Make the ax occupy less space on the (2,2) sized figure
Use smaller fontsize for the ticklabels
or any combination of these. Another, in my opinion better, solution to this "problem" is to use a subplot rather than specifying the Axes's bounds;
ax = fig.add_subplot(111, polar=True, axisbg='#d5de9c')
as this makes it possible to use the method tight_layout() which automatically configures the figure layout to nicely include all elements.
Then over to the real problem at hand; the padding. On a PolarAxes you can set, among other things, the radial placement of the theta-ticks. This is done by specifying the fraction of the polar axes radius where you want the ticklabels to be placed as an argument to the frac parameter of the PolarAxes's set_thetagrids() method. The argument should be a fraction of the axes' radius where you want the ticklabels placed. I.e. for frac < 1 the ticklabels will be placed inside the axes, while for frac > 1 they will be placed outside the axes.
Your code could then be something like this:
import numpy as np
from matplotlib.pyplot import figure, show, grid, tight_layout
# make a square figure
fig = figure(figsize=(2, 2))
ax = fig.add_subplot(111, polar=True, axisbg='#d5de9c')
ax.set_yticklabels([])
r = np.arange(0, 3.0, 0.01)
theta = 2*np.pi*r
ax.plot(theta, r, color='#ee8d18', lw=3)
ax.set_rmax(2.0)
# tick locations
thetaticks = np.arange(0,360,45)
# set ticklabels location at 1.3 times the axes' radius
ax.set_thetagrids(thetaticks, frac=1.3)
tight_layout()
show()
You should try different values for frac to find a value that is best suited for your needs.
If you don't specify a value to the parameter frac as above, i.e. frac has default value None, the code outputs a plot as below. Notice how the radius of the plot is bigger, as the ticklabels don't "occupy as much space" as in the example above.
As of matplotlib 2.1.0, the functionality of the original answer is now deprecated - polar axes now obey to the parameters of ax.tick_params:
ax.tick_params(pad=123)
should do the trick.

Reducing the distance between two boxplots

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])