Skip to main content
 首页 » 编程设计

Python Matplotlib 散点图添加 x 轴标签

2025年05月04日27birdshome

我有以下代码来生成散点图

            import matplotlib.pyplot as plt 
 
              line = plt.figure()     
              plt.plot(xvalue, yvalue) 
              plt.grid(True) 
              plt.savefig("test.png") 
              plt.show() 

这是情节的截图:

我只是想知道是否可以将 x 轴标签更改为字符串。我已将所有标签存储在

    xlabel = ['2015/4/1', '2015/4/11', '2015/4/12', '2015/4/18', '2015/4/19'...] 

matplotlib 是否有任何功能,以便我可以将 x 轴标签设置为“xlabel”中的值?

非常感谢!

我的标签也重叠了,我能做些什么来解决这个问题?谢谢!

请您参考如下方法:

这是我的答案。您的目标是将日期时间绘制为 xticklabel。
我总是做这样的事情。代码如下:

## For example, I have 9 daily value during 2013-04-01 to 2014-04-10 
start = datetime.datetime.strptime("01-04-2013", "%d-%m-%Y") 
end = datetime.datetime.strptime("10-04-2013", "%d-%m-%Y") 
date = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)] 
 
plt.figure(figsize=(12,4)) 
## y is the data I want to plot 
ind = np.arange(len(y)) 
ax=plt.subplot() 
plt.plot(ind,y,lw = 3) 
k = [] 
for i in range(0,len(ind),1): 
    k.append(str(date[i])[0:10]) 
 
plt.xticks(ind,k,rotation=65) 

更新

为了解决重叠问题,我推荐下面的代码:

for label in ax.xaxis.get_ticklabels()[::2]: 
    label.set_visible(False)        

对于一个月的日值,你可以得到这样一个数字: