[英]How to remove in between tick labels in matplotlib python
Im using matplotlib to create a graph, How can I remove ticks but keep the first and last ones only?我使用 matplotlib 创建图形,如何删除刻度但只保留第一个和最后一个? I want to keep their effect though on drawing the grid on the inside of the plot.尽管在绘图内部绘制网格时,我想保持它们的效果。 (remove only the labels to be precise) (为了精确,只删除标签)
Code代码
plt.xlabel("Time [sec]")
plt.ylabel("Load [kN]")
plt.figure(figsize=(6,4.4))
plt.xlim([0, 60])
plt.grid(linestyle='dotted')
plt.axis(linestyle="dotted")
plt.tick_params(axis='y',rotation=90)
ax1= plt.subplot()
ax1.spines['right'].set_color('none')
ax1.spines['bottom'].set_color('none')
ax1.spines['left'].set_color('none')
ax1.spines['top'].set_color('none')
ax1.yaxis.set_major_formatter(FormatStrFormatter('%.3f'))
ax1.tick_params(axis='both', which='major', labelsize=6,colors='#696969')
ax1.tick_params(axis='both', which='minor', labelsize=6,colors='#696969')
ax1.xaxis.set_tick_params(length=0,labelbottom=True)
ax1.yaxis.set_tick_params(length=0,labelbottom=True)
plt.plot(x,y,color='#696969',linewidth='0.5')
plt.show()
Current Figure:当前图:
Goal:目标:
Thanks.谢谢。
You can use xticks
and yticks
to set the ticks you want on the x and y axes, passing to the functions the list of numbers (ticks) you want to be displayed.您可以使用xticks
和yticks
在 x 和 y 轴上设置您想要的刻度,将您想要显示的数字(刻度)列表传递给函数。 For example:例如:
plt.yticks(np.arange(0, 450, step=50))
The tick positions define the positions of the grid.刻度位置定义网格的位置。 So, in the x-direction we would have one every 10. The labels can be set to an empty string, except the first and the last.因此,在 x 方向上,我们每 10 个就有一个。标签可以设置为空字符串,除了第一个和最后一个。
The most complicated part is forcing the first and last grid line to be visible.最复杂的部分是强制第一个和最后一个网格线可见。 Due to rounding, sometimes they can fall outside the plot area.由于四舍五入,有时它们可能会落在绘图区域之外。 Adding an extra epsilon to the limits, should force these grid lines to be visible.添加一个额外的 epsilon 到限制,应该强制这些网格线可见。
The padding for the x and ylabel can be set negative to bring them closer to the axis. x 和 ylabel 的内边距可以设置为负数,使它们更靠近轴。
Note that the figure and the axis should be created before doing operations such as setting labels and grids.注意,在进行设置标签和网格等操作之前,应先创建图形和轴。 The easiest is to call fig, ax = plt.subplots()
before any plotting-related commands.最简单的方法是在任何绘图相关命令之前调用fig, ax = plt.subplots()
。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
# create some dummy data
x = np.linspace(0, 60, 500)
y = (np.sin(x / 5) + 1) * 450000 / 2
fig, ax1 = plt.subplots(figsize=(6, 4.4))
ax1.plot(x, y, color='#696969', linewidth='0.5')
xlims = (0, 60)
xlim_eps = xlims[1] / 200
# use some extra epsilon to force the first and last gridline to be drawn in case rounding would put them outside the plot
ax1.set_xlim(xlims[0] - xlim_eps, xlims[1] + xlim_eps)
xticks = range(xlims[0], xlims[1] + 1, 10)
ax1.set_xticks(xticks) # the ticks define the positions for the grid
ax1.set_xticklabels([i if i in xlims else '' for i in xticks]) # set empty label for all but the first and last
ax1.set_xlabel("Time [sec]", labelpad=-8) # negative padding to put the label closer to the axis
ylims = (0, 450)
ylim_eps = ylims[1] / 200
ax1.set_ylim(ylims[0] - ylim_eps, ylims[1] + ylim_eps)
yticks = range(ylims[0], ylims[1] + 1, 50)
ax1.set_yticks(yticks)
ax1.set_yticklabels([f'{i:.3f}' if i in ylims else '' for i in yticks])
ax1.tick_params(axis='y', rotation=90)
ax1.set_ylabel("Load [kN]", labelpad=-8)
ax1.grid(True, linestyle='dotted')
for dir in ['right', 'bottom', 'left', 'top']:
ax1.spines[dir].set_color('none')
ax1.tick_params(axis='both', which='major', labelsize=6, colors='#696969', length=0)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.