【问题标题】:How to custom ticks and bars in Python?如何在 Python 中自定义刻度和柱?
【发布时间】:2021-02-28 10:35:33
【问题描述】:

我想查看某个事件发生的频率,我的事件何时发生,何时没有发生。

我如何以一种在 x 轴上按顺序显示从 1970 年到 2020 年的年份(1 年间隔)的方式自定义绘图,并且在有数据的地方有条形,在没有数据的地方有空刻度。

list1=[2019, 2016, 2014, 2014, 2011, 2008, 2005, 2004, 2003, 1994, 1992, 1989, 1988, 1984, 1983, 1981, 1980, 1979, 1977, 1975, 1973, 1970]
a=pd.Series(data=list1);a

A=a.value_counts(sort=False).plot.bar(figsize=(15, 3), color='darkblue')

plt.title(' A Occurrence ')

谢谢。

【问题讨论】:

    标签: python time-series bar-chart xticks


    【解决方案1】:

    试试这个:

    import pandas as pd
    import matplotlib.pyplot as plt
    
    list1=[2019, 2016, 2014, 2014, 2011, 2008, 2005, 2004, 2003, 1994, 1992, 1989, 1988, 1984, 1983, 1981, 1980, 1979, 1977, 1975, 1973, 1970]
    a = pd.Series(list1)
    A = a.value_counts().to_frame()
    A.columns = ['cnt']
    idx = np.arange(min(list1), max(list1)+1)
    A = A.reindex(index=idx.tolist(), fill_value=0)
    A.sort_index(axis=0,inplace=True)
    A.plot.bar(figsize=(15, 3), color='darkblue')
    
    plt.title(' A Occurrence ')
    

    【讨论】:

    • 谢谢。但我需要将 1970 年到 2020 年的所有年份都放在我的横轴上。例如,在 1970 和 1973 之间,我需要另外两个刻度,空的,没有柱。在这种情况下,我一眼就可以理解,1970 年和 1973 年有数据,而 1971 年和 1972 年则没有。
    • 你的问题需要这么多年吗?更新了代码和图表。
    猜你喜欢
    • 2020-07-30
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2013-07-19
    相关资源
    最近更新 更多