pyplot,为什么xaxis没有出现?

2024-04-23 11:18:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着根据日期画一些值。但是,不幸的是,在x轴上我没有得到任何值。我觉得这可能是由于两个因素:

  1. 这些值被存储为“日期”,因此使过程复杂化
  2. 由于日期将占据太多的房地产在x轴它变得太混乱,因此这就是为什么我只看到一条黑线。你知道吗

请让我知道如何改进这个,以便我能够得到适当间隔的主要刻度。你知道吗

我现在的代码是:

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

我得到的结果是:

Output


Tags: 代码间隔plot过程showpltsleep因素
1条回答
网友
1楼 · 发布于 2024-04-23 11:18:15

如果您想控制主要和次要记号的位置和格式,您需要使用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

相关问题 更多 >