【问题标题】:Show only integers in matplotlib x-axis tickmarks在 matplotlib x 轴刻度线中仅显示整数
【发布时间】:2020-07-26 11:08:18
【问题描述】:

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 轴标签/刻度线设置为仅显示年份的整数?

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

提前致谢。

【问题讨论】:

    标签: python pandas matplotlib jupyter-notebook jupyter


    【解决方案1】:

    使用参数 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))]
    

    【讨论】:

    • 这太棒了,谢谢@Chris。如果可以,还有一个问题。如何将标签添加到数据点?
    猜你喜欢
    • 1970-01-01
    • 2022-08-04
    • 2016-06-12
    • 1970-01-01
    • 2021-04-03
    • 2013-07-08
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多