pyplot,为什么不显示x轴?

时间:2019-06-27 15:55:36

标签: python plot

我正在尝试针对日期绘制一些值。但是,不幸的是我没有在x轴上获得任何值。我认为这可能是由于两个因素造成的:

  1. 这些值存储为“日期”,从而使过程变得复杂
  2. 由于日期会在x轴上占据过多的空间,因此变得过于混乱,因此这就是为什么我只看到黑线的原因。

请让我知道我该如何改进它,以便能够获得适当间隔的主要刻度。

我当前的代码是:

fig1 = plt.plot(Sleep['dateOfSleep'], Sleep['TotalDeepSleep'])
plt.show()
plt.clf

我得到的输出是:

Output

1 个答案:

答案 0 :(得分:1)

如果要控制主要和次要刻度线的位置和格式,则需要使用date tickers。这是我经常用于跨越多个月的绘图时间序列的函数:

def format_xaxis(fig):
     # here I am setting the major ticks to each decade
     # Change to something appropriate for your data
     major= dates.MonthLocator(bymonthday=1)

     #Here I am setting each minor ticks to mid-decade 
     # Change to something appropriate for your data    
     minor=dates.MonthLocator(bymonthday=15)

     #Here I am setting each major ticks and minor tick formatting
     # Change to something appropriate for your data 
     #look at http://strftime.org/ for other options
     majorfmt = dates.DateFormatter('%B')
     minorfmt = dates.DateFormatter('%d')

     # Set the locators and formats for all of the subplots axes
     [i.xaxis.set_major_locator(major) for i in fig.axes]
     [i.xaxis.set_minor_locator(minor) for i in fig.axes]
     [i.xaxis.set_major_formatter(majorfmt) for i in fig.axes]
     [i.xaxis.set_minor_formatter(minorfmt) for i in fig.axes]

     # Here I am offsetting the major ticks down so they dont overlap with minor tick lables
     [i.get_xaxis().set_tick_params(which='major', pad=15) for i in fig.axes]

     #make them look nice
     for t in fig.axes:
         for tick in t.xaxis.get_major_ticks():
             tick.label1.set_horizontalalignment('center')
         for label in t.get_xmajorticklabels() :
             label.set_rotation(0)
             label.set_weight('bold')
         for label in t.xaxis.get_minorticklabels():
             label.set_fontsize('small')   

您可以将dates.MonthLocator换成适合您数据的任何定位器。只需查看我提供的链接即可。

一个小例子:

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

df = pd.DataFrame({'Date':pd.date_range(start = '2015-01-01', end = '2015-05-01'), 'TotalDeepSleep':np.random.randint(0,140,size=121)})


fig,ax = plt.subplots()
ax.plot_date(df['Date'], df['TotalDeepSleep'])

format_xaxis(fig)

enter image description here