Python Matplotlib散点图添加x轴标签

时间:2016-04-06 01:44:22

标签: python python-3.x matplotlib scatter-plot

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

            import matplotlib.pyplot as plt

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

以下是情节的截图: enter image description here

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

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

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

很多人!

另外我的标签是重叠的,我能做些什么来解决这个问题? THX!

enter image description here

2 个答案:

答案 0 :(得分:5)

这是我的答案。你的目标是将日期时间绘制为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)

enter image description here

更新

要解决重叠问题,我建议使用以下代码:

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

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

enter image description here

答案 1 :(得分:0)

执行:

plt.xticks(xs, labels)

其中xs是代码的位置列表,labels是标签列表。