[英]How to change separation between tick labels and axis labels in Matplotlib
[英]How to remove in between tick labels in matplotlib python
我使用 matplotlib 创建图形,如何删除刻度但只保留第一个和最后一个? 尽管在绘图内部绘制网格时,我想保持它们的效果。 (为了精确,只删除标签)
代码
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()
当前图:
目标:
谢谢。
您可以使用xticks
和yticks
在 x 和 y 轴上设置您想要的刻度,将您想要显示的数字(刻度)列表传递给函数。 例如:
plt.yticks(np.arange(0, 450, step=50))
刻度位置定义网格的位置。 因此,在 x 方向上,我们每 10 个就有一个。标签可以设置为空字符串,除了第一个和最后一个。
最复杂的部分是强制第一个和最后一个网格线可见。 由于四舍五入,有时它们可能会落在绘图区域之外。 添加一个额外的 epsilon 到限制,应该强制这些网格线可见。
x 和 ylabel 的内边距可以设置为负数,使它们更靠近轴。
注意,在进行设置标签和网格等操作之前,应先创建图形和轴。 最简单的方法是在任何绘图相关命令之前调用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.