如何在matplotlib python中删除中间的记号标签

2024-03-29 02:21:00 发布

您现在位置: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()

当前数字:

Current Figure

目标:

Goal

谢谢


Tags: nonewhichpltparamscolorsetdottedaxis
2条回答

您可以使用xticksyticks在x轴和y轴上设置所需的记号,并将要显示的数字列表(记号)传递给函数。例如:

plt.yticks(np.arange(0, 450, step=50))

记号位置定义栅格的位置。所以,在x方向上,我们每10个就有一个。标签可以设置为空字符串,第一个和最后一个除外

最复杂的部分是强制第一条和最后一条网格线可见。由于成圆,有时它们可能落在绘图区域之外。在限制中添加一个额外的ε,应强制这些网格线可见

x和Y标签的填充可以设置为负数,以使它们更靠近轴

请注意,图形和轴应在执行设置标签和轴网等操作之前创建。最简单的方法是在任何打印相关命令之前调用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()

enter image description here

相关问题 更多 >