matplotlib:为日期时间值的cdf定制x轴刻度

时间:2018-06-04 01:10:49

标签: python pandas matplotlib cdf

我有一张日期时间列表的cdf。运行以下代码后,其中objDate是日期时间值列表(格式:%Y-%m-%d),我在x轴上得到带有刻度的cdf,显示值范围内的每隔一年。如何通过指定以下内容获得沿x轴刻度的自定义标签:

1.范围(分年和最大年份)
2.间隔(比如说相隔6个月,所以刻度标签就像01 / 17,17 / 17,11 / 18,07 / 18,......)

import matplotlib.pyplot as plt
import pandas as pd

ser = pd.Series(objDate)
ser.hist(cumulative=True, density=1, bins=500, histtype='step')
plt.show()

1 个答案:

答案 0 :(得分:2)

关于第二个问题,您可以使用matplotlib.dates定位器和格式化程序。那些在hist

的情况下工作得很好
import matplotlib.pyplot as plt
plt.rcParams['axes.axisbelow'] = True
import matplotlib.dates as dates
import numpy as np; np.random.seed(42)
import pandas as pd

objDate = dates.num2date(np.random.normal(735700, 300, 700))

ser = pd.Series(objDate)
ax = ser.hist(cumulative=True, density=1, bins=500, histtype='step', linewidth=2)

ax.xaxis.set_major_locator(dates.MonthLocator([1,7]))
ax.xaxis.set_major_formatter(dates.DateFormatter("%m/%y"))
plt.setp(ax.get_xticklabels(), rotation=60)

plt.show()

enter image description here

对于第一个问题,这并不容易,因为matplotlib总是假设要勾选完整的轴。解决方案是将正在使用的定位器子类化并允许它采用限制性参数。

from datetime import datetime
import matplotlib.pyplot as plt
plt.rcParams['axes.axisbelow'] = True
import matplotlib.dates as dates
import numpy as np; np.random.seed(42)
import pandas as pd

objDate = dates.num2date(np.random.normal(735700, 300, 700))

ser = pd.Series(objDate)
ax = ser.hist(cumulative=True, density=1, bins=500, histtype='step', linewidth=2)


class RestrictedLocator(dates.MonthLocator):
    def __init__(self, dmin=None, dmax=None, **kw):
        self.dmin = dmin
        self.dmax = dmax
        dates.MonthLocator.__init__(self, **kw)

    def __call__(self):
        try:
            dmin, dmax = self.viewlim_to_dt()
        except ValueError:
            return []

        self.dmin = self.dmin.replace(tzinfo=dmin.tzinfo)
        self.dmax = self.dmax.replace(tzinfo=dmin.tzinfo)
        dmin = np.max([dmin, self.dmin])
        dmax = np.min([dmax, self.dmax])
        return self.tick_values(dmin, dmax)


loc = RestrictedLocator(dmin=datetime(2015,1,1), 
                        dmax = datetime(2017,12,31),
                        bymonth=[1,7])

ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(dates.DateFormatter("%m/%y"))
plt.setp(ax.get_xticklabels(), rotation=60)

plt.show()

enter image description here