繁体   English   中英

如何将数据的所有标签添加到 matplotlib 图表的 x 轴?

[英]How to i add all the labels of my data to the x-axis of a matplotlib graph?

我希望我的图表显示我的 x 轴的所有数据,而不是自动删除一些点。 我的图表应该显示从 2011 年到 2020 年的所有年份,除了它每两年跳过一次。 请帮忙。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

x = [2011,2012,2013,2014,2015,2016,2017,2018,2019,2020];
y = [139.1,128.6,115.1,109.4,104.1,111.1,119.4,128.3,137.9,147];

fig, (ax2) = plt.subplots(nrows=1, ncols=1, figsize = (8,4))


ax2.scatter(x=x, y=y, marker='o', c='grey', edgecolor= 'b')
ax2.set_title('Retail sales in South-Africa in billion US$') ##$$ makes text italic
ax2.set_xlabel('$Year$')
ax2.set_ylabel('Retail sales in billion US$')
ax2.grid(which = 'major', axis= 'y', linestyle = ':')
ax2.plot(x, y, c='b', )

for x,y in zip(x,y):

    label = y

    plt.annotate(label, # this is the text
                 (x,y), # this is the point to label
                 textcoords="offset points", # how to position the text
                 xytext=(0,15), # distance from text to points (x,y)
                 ha='center')

plt.xticks()
plt.yticks()

plt.tight_layout()
plt.show()
```

看来您做对了:查看此链接

为了让它按照您希望的方式工作,我更改的唯一代码行是plt.xticks() ,如下所示:

plt.xticks([2011,2012,2013,2014,2015,2016,2017,2018,2019,2020])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM