Python Matplotlib 散点图添加 x 轴标签

标签 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”中的值?

非常感谢!

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

enter image description here

最佳答案

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

关于Python Matplotlib 散点图添加 x 轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440016/

相关文章:

python - 区分pyparsing中的匹配项

python - 使用 AJAX 通过网络调用 python 函数?

python - 从列表中过滤字符串

python - Pandas json_normalize 返回 KeyError

python-2.7 - 导入 matplotlib._png 作为 _png 导入 : Error: DLL load failed: The specified module could not be found

python - 为什么我的按键 Action 不能正常工作?

python - 如何改进删除重复算法?

python - 日历在 tkinter 中未对齐

python - matplotlib 中的非闭合轮廓?

python - 来自带有 matplotlib 的数组的 3D 曲线的线条颜色