簡體   English   中英

Matplotlib麻煩繪制x標簽

[英]Matplotlib trouble plotting x-labels

使用set_xlim有問題。 (可能由於日期時間對象?)

這是我的代碼(在ipython筆記本中執行):

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import datetime

date_list = [datetime.datetime(2015, 6, 20, 0, 0), datetime.datetime(2015, 6, 21, 0, 0), datetime.datetime(2015, 6, 22, 0, 0), datetime.datetime(2015, 6, 23, 0, 0), datetime.datetime(2015, 6, 24, 0, 0), datetime.datetime(2015, 6, 25, 0, 0), datetime.datetime(2015, 6, 26, 0, 0)]
count_list = [11590, 10743, 27369, 31023, 30569, 31937, 30205]

fig=plt.figure(figsize=(10,3.5))
ax=fig.add_subplot(111)

width = 0.8

tickLocations = np.arange(7)

ax.set_title("Turnstiles Totals for Lexington Station C/A A002 Unit R051 from 6/20/15-6/26-15")
ax.bar(date_list, count_list, width, color='wheat', edgecolor='#8B7E66', linewidth=4.0)
ax.set_xticklabels(date_list, rotation = 315, horizontalalignment = 'left')

這給了我:

在此處輸入圖片說明

但是,當我嘗試使用此代碼在最左邊和最右邊留出一些額外的空間時:

ax.set_xlim(xmin=-0.6, xmax=0.6)

我收到這個巨大的錯誤(這只是最下面的代碼段):

    223         tz = _get_rc_timezone()
    224     ix = int(x)
--> 225     dt = datetime.datetime.fromordinal(ix)
    226     remainder = float(x) - ix
    227     hour, remainder = divmod(24 * remainder, 1)

ValueError: ordinal must be >= 1

知道伙計們怎么了嗎? 謝謝!

由於各種歷史原因,matplotlib在幕后使用內部數字日期格式。 實際的x值采用這種數據格式,其中0.0為1900年1月1日,而相差1.0則相當於1天。 不允許使用負值。

您收到的錯誤是因為您試圖將x限制設置為包括負范圍。 即使沒有負數,它的范圍也是1900年1月1日。

無論如何,聽起來您想要的根本不是ax.set_xlim 嘗試使用ax.margins(x=0.05)在x方向上添加5%的填充。

舉個例子:

import matplotlib.pyplot as plt
import numpy as np
import datetime

count_list = [11590, 10743, 27369, 31023, 30569, 31937, 30205]
date_list = [datetime.datetime(2015, 6, 20, 0, 0),
             datetime.datetime(2015, 6, 21, 0, 0),
             datetime.datetime(2015, 6, 22, 0, 0),
             datetime.datetime(2015, 6, 23, 0, 0),
             datetime.datetime(2015, 6, 24, 0, 0),
             datetime.datetime(2015, 6, 25, 0, 0),
             datetime.datetime(2015, 6, 26, 0, 0)]

fig, ax = plt.subplots(figsize=(10,3.5))
ax.set_title("Turnstiles Totals for Lexington Station C/A A002 Unit R051 from "
             "6/20/15-6/26-15")

# The only difference is the align kwarg: I've centered the bars on each date
ax.bar(date_list, count_list, align='center', color='wheat',
       edgecolor='#8B7E66', linewidth=4.0)

# This essentially just rotates the x-tick labels. We could have done
# "fig.autofmt_xdate(rotation=315, ha='left')" to match what you had.
fig.autofmt_xdate()

# Add the padding that you're after. This is 5% of the data limits.
ax.margins(x=0.05)

plt.show()

在此處輸入圖片說明

請注意,如果您想將x限制在每個方向上精確地擴展為0.6,則可以執行以下操作:

xmin, xmax = ax.get_xlim()
ax.set_xlim([xmin - 0.6, xmax + 0.6])

但是,只要您對“填充”表示的是當前軸限制的比率,則ax.margins(percentage)會容易得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM