remove tick labels in Python but keep gridlines - python

I have a Python script which is producing a plot consisting of 3 subplots all in 1 column.
In the middle subplot, I currently have gridlines, but I want to remove the x axis tick labels.
I have tried
ax2.axes.get_xaxis().set_ticks([])
but this seems to remove the gridlines also.
How can I remove the tick labels and keep the gridlines please?

Please try this:
plt.grid(True)
ax2.axes.get_xaxes().set_ticks([])
Or maybe this:
from matplotlib.ticker import NullFormatter
ax2.axes.get_xaxis().set_major_formatter(NullFormatter())

Related

Vertically offset tick labels in Matplotlib

I want tick labels to be placed above the tick instead of centered on the tick.
This is how it looks now:
This is how I want it to look:
I've read about tick label formatting here but I could only figure out how modify horizontal padding. I think I need to modify vertical padding. Does anyone have an idea how I could do this?
You can set the vertical alignment of the tick labels directly to shift them up.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(100,)
fig, ax = plt.subplots(2, 1)
ax[0].plot(data)
ax[0].set_title("No shift")
ax[1].plot(data)
for tick in ax[1].get_yticklabels():
tick.set_verticalalignment("bottom")
ax[1].set_title("With shift")
fig.tight_layout()
plt.show()
You can see that in the first subplot the labels are centered on the ticks, while on the bottom plot they are above it.

Black bar covering my x labels for matplotlib plot?

I am trying to play a figure and I am having a black box pop up on the bottom of the plot where the x labels should be. I tried this command from a similar question on here in the past:
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
But the problem was still the same. Here is my current code:
import pylab
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
df['date'] = df['date'].astype('str')
pos = np.arange(len(df['date']))
plt.bar(pos,df['value'])
ticks = plt.xticks(pos, df['value'])
And my plot is attached here. Any help would be great!
pos = np.arange(len(df['date'])) and ticks = plt.xticks(pos, df['value']) are causing the problem you are having. You are putting an xtick at every value you have in the data frame.
Don't know how you data looks like and what's the most sensible way to do this. ticks = plt.xticks(pos[::20], df['value'].values[::20], rotation=90) will put a tick every 20 rows that would make the plot more readable.
It actually is not a black bar, but rather all of your x-axis labels being crammed into too small of a space. You can try rotating the axis labels to create more space or just remove them all together.

Unable to remove yticks from pyplot subplots

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)

customize ticks label when sharex is on in matplotlib

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)

Matplotlib: How do I have the xtick labels apear on the other side of the x-axis?

In this bar chart:
How do I make the x-axis labels appear in the bars of the bar-chart and left-aligned with the x-axis?
I tried the ax.xaxis.labelpad() method but it does not seem to do anything.
you can set the y location of the ticks when you call set_xticklabels. So, if you set y to something small but positive, it should be placed inside the bars.
For example:
import matplotlib.pyplot as plt
fig,ax = plt.subplots(1)
ax.bar([0,1,2,3],[7900,9400,8700,9990],facecolor='#5080B0',edgecolor='k',width=0.3)
ax.set_xticks([0.15,1.15,2.15,3.15])
ax.set_xticklabels(['beek1','beek2','orbath','Kroo'],
rotation='vertical',y=0.05,va='bottom')
Produces the following plot:

Categories