在Matplotlib X轴刻度中仅显示整数

时间:2020-04-13 19:46:19

标签: python pandas matplotlib jupyter-notebook jupyter

matplotlib的新手,并从原理上类似于以下内容的数据集创建了一个简单的折线图。我们称该数据框为“ cardata”

|------- |--------|------------|---------|
|   id   | year   |  some_var  |  count  |                                               
---------|--------|------------|---------|
|   1    |  2016  |     car    |    1    |                                      
|   2    |  2016  |     car    |    1    |  
|   3    |  2017  |     car    |    1    |   
|   4    |  2017  |     car    |    1    |   
|   5    |  2018  |     car    |    1    |                                      
|   6    |  2018  |     car    |    1    |  
|   7    |  2018  |     car    |    1    |   
|   8    |  2019  |     car    |    1    | 
|   9    |  2019  |     car    |    1    | 
|  10    |  2020  |     car    |    1    | 

我希望按年份汇总计数,以便查看每年有多少次“汽车”出现。

我已经使用以下代码实现了

cardata.groupby(['year']).count()['some_var'].plot()

这给了我一个我可以使用的图,但是x轴像这样...

| 2016 | 2016.5 | 2017 | 2017.5 | 2018 | 2018.5 | etc etc 

问题1)如何设置x-asxis标签/刻度线仅显示年份的整数?

问题2)例如,如何从情节中排除“ 2020”年?

谢谢。

1 个答案:

答案 0 :(得分:2)

布尔索引,groupby和带有参数xticks的绘图:

g = df[df['year'] != 2020].groupby('year').count()['some_var']
g.plot(xticks=g.index)

一种绘制标签的方法是使用matplotlib和列表理解。代码的打击将绘制y值,但实际上可以是任何值:

import matplotlib.pyplot as plt
g = df[df['year'] != 2020].groupby('year').count()['some_var']

g.plot(xticks=g.index)

[plt.annotate(y, (x,y), textcoords="offset points",
              xytext=(0,10), ha='center') for x,y in list(zip(g.index, g))]

enter image description here