Skip to main content
 首页 » 编程设计

python之在 x 轴上绘制一些数字

2025年05月04日26zfyouxi

我的问题与使用 matplotlib 库生成的图形格式有关。

所以,在 x 轴上,我有从 1 到 100 的整数,但在我的代码中,我只绘制与某些数字相关的数据(例如 1、5、77、86、97)。

最后,我的代码显示了一个 x 轴从 1 到 100 的图形。

如何才能只显示所需的数字 (1,5,77,86,97)?

我的代码如下所示:

def Plot(self,x,y, steps, nb,bool):   
    if(bool == False): 
 
        labelfont = { 
                'family' : 'sans-serif',  # (cursive, fantasy, monospace, serif) 
                'color'  : 'black',       # html hex or colour name 
                'weight' : 'normal',      # (normal, bold, bolder, lighter) 
                'size'   : 20,            # default value:12 
                } 
 
        titlefont = { 
                'family' : 'serif', 
                'color'  : 'black', 
                'weight' : 'bold', 
                'size'   : 20, 
                } 
 
        x = np.array(x) 
        y = np.array(y) 
        pylab.plot(x, y, 
                 'darkmagenta',                       # colour 
                 linestyle='',                      # line style 
                 linewidth=10,                       # line width 
                 marker = '+', 
                 mew=6, ms=12) 
 
        axes = plt.gca() 
        axes.grid(True) 
        axes.set_xlim([1, x_max)            # x-axis bounds 
        axes.set_ylim([1, nb])              # y-axis bounds 
 
        pylab.title('Title' , fontdict=titlefont) 
        pylab.xlabel('x', fontdict=labelfont) 
        pylab.ylabel('y', fontdict=labelfont) 
 
        pylab.subplots_adjust(left=0.15)        # prevents overlapping of the y label 
    else: 
        test_steps.insert(0,"") 
        pylab.yticks(nb,  steps,rotation=0, size=10) 
        pylab.margins(0.2) 
        pylab.xticks(np.arange(0, x_max, 1.0),rotation=90, size=10) 
        # Tweak spacing to prevent clipping of tick-labels 
        pylab.subplots_adjust(bottom=0.15) 
        F = pylab.gcf() 
        DefaultSize = F.get_size_inches() 
        if x_max < 100 and len(steps) < 100: 
            Xx = 2.5 
            Yy = 2.5 
        elif x_max < 200 and len(steps) < 200: 
            Xx = 5 
            Yy = 5 
        elif ix_max < 300 and len(steps) < 300: 
            Xx = 8 
            Yy = 8 
        elif x_max < 400 and steps < 400: 
            Xx = 10 
            Yy = 10 
        elif x_max < 500 and steps < 500: 
            Xx = 12 
            Yy = 12 
        else: 
            Xx = 15 
            Yy = 15 
        F.set_size_inches((DefaultSize[0]*Xx , DefaultSize[1]*Yy)) 
        F.savefig('Out.png', bbox_inches='tight') 
        pylab.close(F) 

请您参考如下方法:

这样就可以了:

import matplotlib.pyplot as plt 
x = y = list(range(100)) 
idx = [1,5,77,86,97] 
new_y = [y[i] for i in idx] 
plt.plot(range(len(idx)), new_y, 'o-') 
plt.xticks(range(len(idx)),idx) 
plt.show() 

如果您只想要点,只需删除 -:

plt.plot(range(len(idx)), new_y, 'o') 
#                              ---^--- instead of 'o-'