Remove xticks in a matplotlib plot?
The plt.tick_params
method is very useful for stuff like this. This code turns off major and minor ticks and removes the labels from the x-axis.
Note that there is also ax.tick_params
for matplotlib.axes.Axes
objects.
from matplotlib import pyplot as plt
plt.plot(range(10))
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
plt.show()
plt.savefig('plot')
plt.clf()
Python hide ticks but show tick labels
You can set the tick length to 0 using tick_params
(http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1],[1])
ax.tick_params(axis=u'both', which=u'both',length=0)
plt.show()
how do I remove xticks and yticks from the below example
IIUC, I believe you can use tick_params(width=0)
. Adjust the below as necessary depending on which ticks you want to hide.
host.tick_params(width=0)
par1.tick_params(width=0)
par2.tick_params(width=0)
Output:
Remove xticks and yticks of gridspec matlibplot plot
You should be using matplotlib.axes.Axes.tick_params()
instead of matplotlib.pyplot.tick_params()
. The latter will apply only to the 'current', in this case the most recently created, axes instance - the former allows you to apply the tick params to any axes instance. Consider:
for ax in fig.get_axes():
ax.tick_params(bottom=False, labelbottom=False, left=False, labelleft=False)
Which will produce
Remove specific tick markers of a matplotlib plot, how?
You could manually set which x_ticks should be in the plot by explicitly saving the location and the text as following:
xticks = ax.xaxis.get_major_ticks()
visible_xticks_locs = []
visible_xticks_labels = []
for x_tick, y_tick in ax.get_lines()[0].get_xydata():
if y_tick > -0.5:
visible_xticks_locs.append(int(x_tick))
visible_xticks_labels.append(xticks[int(x_tick)])
ax.set_xticks(ticks=visible_xticks_locs, labels=visible_xticks_labels)
How to remove or hide y-axis ticklabels from a matplotlib / seaborn plot
seaborn
is used to draw the plot, but it's just a high-level API formatplotlib
.- The functions called to remove the y-axis labels and ticks are
matplotlib
methods.
- The functions called to remove the y-axis labels and ticks are
- After creating the plot, use
.set()
. .set(yticklabels=[])
should remove tick labels.- This doesn't work if you use
.set_title()
, but you can use.set(title='')
- This doesn't work if you use
.set(ylabel=None)
should remove the axis label..tick_params(left=False)
will remove the ticks.- Similarly, for the x-axis: How to remove or hide x-axis labels from a seaborn / matplotlib plot?
Example 1
import seaborn as sns
import matplotlib.pyplot as plt
# load data
exercise = sns.load_dataset('exercise')
pen = sns.load_dataset('penguins')
# create figures
fig, ax = plt.subplots(2, 1, figsize=(8, 8))
# plot data
g1 = sns.boxplot(x='time', y='pulse', hue='kind', data=exercise, ax=ax[0])
g2 = sns.boxplot(x='species', y='body_mass_g', hue='sex', data=pen, ax=ax[1])
plt.show()
Remove Labels
fig, ax = plt.subplots(2, 1, figsize=(8, 8))
g1 = sns.boxplot(x='time', y='pulse', hue='kind', data=exercise, ax=ax[0])
g1.set(yticklabels=[]) # remove the tick labels
g1.set(title='Exercise: Pulse by Time for Exercise Type') # add a title
g1.set(ylabel=None) # remove the axis label
g2 = sns.boxplot(x='species', y='body_mass_g', hue='sex', data=pen, ax=ax[1])
g2.set(yticklabels=[])
g2.set(title='Penguins: Body Mass by Species for Gender')
g2.set(ylabel=None) # remove the y-axis label
g2.tick_params(left=False) # remove the ticks
plt.tight_layout()
plt.show()
Example 2
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# sinusoidal sample data
sample_length = range(1, 1+1) # number of columns of frequencies
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([(np.cos(t*rads)*10**67) + 3*10**67 for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])
df.reset_index(inplace=True)
# plot
fig, ax = plt.subplots(figsize=(8, 8))
ax.plot('radians', 'freq: 1x', data=df)
Remove Labels
# plot
fig, ax = plt.subplots(figsize=(8, 8))
ax.plot('radians', 'freq: 1x', data=df)
ax.set(yticklabels=[]) # remove the tick labels
ax.tick_params(left=False) # remove the ticks
Why can't I remove pyplot tick labels?
You can try specifying xticks and xticklabels from the setp function to force label deletions
plt.setp(ax1, xticks=[1,2,3,4,5],
xticklabels=['','','','',''],
yticks=[1,2,3,4,5],
yticklabels=["",'','',''])
How to remove or hide x-axis labels from a seaborn / matplotlib plot
- After creating the boxplot, use
.set()
. .set(xticklabels=[])
should remove tick labels.- This doesn't work if you use
.set_title()
, but you can use.set(title='')
.
- This doesn't work if you use
.set(xlabel=None)
should remove the axis label..tick_params(bottom=False)
will remove the ticks.- Similarly, for the y-axis: How to remove or hide y-axis ticklabels from a matplotlib / seaborn plot?
fig, ax = plt.subplots(2, 1)
g1 = sb.boxplot(x="user_type", y="Seconds", data=df, color = default_color, ax = ax[0], sym='')
g1.set(xticklabels=[])
g1.set(title='User-Type (0=Non-Subscriber, 1=Subscriber)')
g1.set(xlabel=None)
g2 = sb.boxplot(x="member_gender", y="Seconds", data=df, color = default_color, ax = ax[1], sym='')
g2.set(xticklabels=[])
g2.set(title='Gender (0=Male, 1=Female, 2=Other)')
g2.set(xlabel=None)
Example
With xticks and xlabel
import seaborn as sns
import matplotlib.pyplot as plt
# load data
exercise = sns.load_dataset('exercise')
pen = sns.load_dataset('penguins')
# create figures
fig, ax = plt.subplots(2, 1, figsize=(8, 8))
# plot data
g1 = sns.boxplot(x='time', y='pulse', hue='kind', data=exercise, ax=ax[0])
g2 = sns.boxplot(x='species', y='body_mass_g', hue='sex', data=pen, ax=ax[1])
plt.show()
Without xticks and xlabel
fig, ax = plt.subplots(2, 1, figsize=(8, 8))
g1 = sns.boxplot(x='time', y='pulse', hue='kind', data=exercise, ax=ax[0])
g1.set(xticklabels=[]) # remove the tick labels
g1.set(title='Exercise: Pulse by Time for Exercise Type') # add a title
g1.set(xlabel=None) # remove the axis label
g2 = sns.boxplot(x='species', y='body_mass_g', hue='sex', data=pen, ax=ax[1])
g2.set(xticklabels=[])
g2.set(title='Penguins: Body Mass by Species for Gender')
g2.set(xlabel=None)
g2.tick_params(bottom=False) # remove the ticks
plt.show()
How to remove the first and last minor tick month labels on matplotlib?
Try setting your x-axis limit to values between 0 and 365. Sometimes matplotlib uses values a little outside of your data. This way, the first Dec and last Jan are automatically eliminated from the plot.
Here I modified your code with 1 argument: plt.xlim(0,365)
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
df = pd.DataFrame(np.random.randint(0,100,size=(365, 2)), columns=list('AB'))
df.index = pd.date_range(start='1/1/2022', end='12/31/2022').strftime('%b-%d')
plt.figure()
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.MonthLocator(bymonthday=16))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%b'))
for tick in ax.xaxis.get_minor_ticks():
tick.tick1line.set_markersize(0)
tick.tick2line.set_markersize(0)
tick.label1.set_horizontalalignment('center')
plt.xlim(0,365)
plt.plot(df['A'], linewidth=0.5, color='tab:red')
plt.show()
Related Topics
Pandas New Column from Groupby Averages
Generating HTML Documents in Python
Getting Segmentation Fault Core Dumped Error While Importing Robjects from Rpy2
Python: What's the Difference Between Pythonbrew and Virtualenv
Vscode -- How to Set Working Directory for Debugging a Python Program
What Is the Cause of the Bad Request Error When Submitting Form in Flask Application
How to Install Python Opencv Through Conda
Pandas Get Column Average/Mean
Inverting a Dictionary with List Values
Why Is Variable1 += Variable2 Much Faster Than Variable1 = Variable1 + Variable2
How to Add Sum to Zero Constraint to Glm in Python
How to Integrate a Standalone Python Script into a Rails Application
Is There Something Like Bpython for Ruby
Call Python Function from Matlab
How to Operate on a Dataframe with a Series for Every Column
Plotly: How to Define Colors in a Figure Using Plotly Graph Objects and Plotly Express