2016-02-19 58 views
1

編輯:Matplotlib版本是1.4.2, numpy的版本是1.8.2Matplotlib XTICK%H後追加%F:%M%:S於圖表

我建立從csv文件的曲線圖具有以下格式

08:21:05,41.0 
08:22:05,41.0 
08:23:05,41.0 

第一列是時間(當然)和第二列是一釐米的測量。

我正在更新一個應用程序,我寫了一個測量坑水坑水位到Python3的活動,它需要將 的日期從字節轉換爲str,因爲它拋出了一個錯誤。在Python2下可以接受的字節數。

該圖形使用以下代碼創建;

import time 
import numpy as np 
import matplotlib as mpl 
mpl.use('Agg') 
import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 
from matplotlib import rcParams 
rcParams.update({'figure.autolayout': True}) 

def bytesdate2str(fmt, encoding='utf-8'): 
    '''Convert strpdate2num from bytes to string as required in Python3. 

    This is a workaround as described in the following tread; 
    https://github.com/matplotlib/matplotlib/issues/4126/ 

    Credit to github user cimarronm for this workaround. 
    ''' 

    strconverter = mdates.strpdate2num(fmt) 

    def bytesconverter(b): 
     s = b.decode(encoding) 
     return strconverter(s) 
    return bytesconverter 

def graph(csv_file, filename, bytes2str): 
    '''Create a line graph from a two column csv file.''' 

    unit = 'metric' 
    date, value = np.loadtxt(csv_file, delimiter=',', unpack=True, 
          converters={0: bytes2str} 
          ) 
    fig = plt.figure(figsize=(10, 3.5)) 
    fig.add_subplot(111, axisbg='white', frameon=False) 
    rcParams.update({'font.size': 9}) 
    plt.plot_date(x=date, y=value, ls='solid', linewidth=2, color='#FB921D', 
        fmt=':' 
       ) 
    title = "Sump Pit Water Level {}".format(time.strftime('%Y-%m-%d %H:%M')) 
    title_set = plt.title(title) 
    title_set.set_y(1.09) 
    plt.subplots_adjust(top=0.86) 

    if unit == 'imperial': 
     plt.ylabel('inches') 
    if unit == 'metric': 
     plt.ylabel('centimeters') 

    plt.xlabel('Time of Day') 
    plt.xticks(rotation=30) 
    plt.grid(True, color='#ECE5DE', linestyle='solid') 
    plt.tick_params(axis='x', bottom='off', top='off') 
    plt.tick_params(axis='y', left='off', right='off') 
    plt.savefig(filename, dpi=72) 


csv_file = "file.csv" 
filename = "today.png" 

bytes2str = bytesdate2str('%H:%M:%S') 
graph(csv_file, filename, bytes2str) 

在Python 3中使用matplotlib我必須將日期從字節轉換爲str,這是函數bytesdate2str的作用。 這是另一個github用戶在問題線程中編寫的解決方法。我試了一下,現在它確實創建了圖形。

但是,x軸上的時間現在追加了%f到最後。我已經能夠在日期格式 周圍的matplotlib網站上找到一些文檔,但我很難找出如何刪除。%f我認爲這代表一個浮點數。

這裏是什麼xticks之前看起來像Python2 下Good xticks image

這裏是xticks的樣子從字節轉換後爲str Bad xticks image

如何從的末尾移除%F時間?這是我使用matplotlib的唯一東西,並且當它來到 時,它是一個新手。我已經長時間地ban住了我的頭。感謝您提供的任何見解。

回答

0

%f是日期時間模塊中的微秒字段。我認爲你的東西有問題bytes2str = bytesdate2str('%H:%M:%S')

相關問題