2017-02-09 76 views
0

我在GUI中有一个图形,该图形通过点击按钮打开。它从一个不断更新的csv文件打开,因此在开始时进行计数,我想限制x轴的条目数。MatPlotLib带有日期的X轴

但是,这条阴谋对四条线有效,我一直无法改进x轴,我想要做的是;

  1. 旋转字体
  2. 删除尾随零的日期
  3. 可能更改日期格式,以DMY H:M

下面的脚本是我到目前为止有:

def open_graph(): 
    import numpy as np 
    import matplotlib.pyplot as plt 
    import datetime as dt 
    from dateutil import parser 
    from csv import reader 
    with open('Voltage_Readings.csv','r') as f: 
     data = list(reader(f)) 

    file=open('Voltage_Readings.csv') 
    numlines=(len(file.readlines())-1) 
    start=numlines-100 
    end=numlines 

    fig=plt.figure() 
    ax=plt.subplot(111) 

    DTG = [parser.parse(i[1]) for i in data[start:end]] 
    Battery_Level = [i[2] for i in data[start:end]] 
    Gene_Supply = [i[3] for i in data[start:end]] 
    Solar_Supply = [i[4] for i in data[start:end]] 
    Wind_Supply = [i[5] for i in data[start:end]] 

    plt.plot(DTG, Battery_Level,'-r', label='Battery') 
    plt.plot(DTG, Gene_Supply,'-y', label='Gene') 
    plt.plot(DTG, Solar_Supply,'-b', label='Solar') 
    plt.plot(DTG, Wind_Supply,'-g', label='Wind') 

    box = ax.get_position() 
    ax.set_position([box.x0, box.y0, box.width *0.85, box.height]) 
    ax.legend(bbox_to_anchor=(1, 1),loc=2) 

    plt.title('VOLTAGE MEASUREMENTS FROM POWER SOURCES') 
    plt.xlabel('Time') 
    plt.ylabel('Voltage') 

    plt.show() 

我希望任何帮助都能够实现这一点,因为我仍然在学习。

回答

0

这是一个更好的答案:

您plt.show前只需添加这()命令:

fig.autofmt_xdate() 
import matplotlib.dates as mdates 
ax.fmt_xdata = mdates.DateFormatter('%d-%m-%Y %H:%M') 
datetimefmt = mdates.DateFormatter("%d-%m-%Y %H:%M") 
ax.xaxis.set_major_formatter(datetimefmt) 

运行autofmt_xdate使倾斜的日期。 设置ax.fmt_xdata将鼠标悬停在某个点上时设置日期格式。 正在运行ax.xaxis.set_major_formatter在x轴上设置日期格式。

有趣的是,在我自己的matplotlib代码中,我已经在x轴上完成了自己的日期格式,因为我没有意识到这些自动格式化功能。我将不得不修改我的代码以使用matplotlib中已有的代码。

鲍比

+0

@bobbydurrettdba,感谢您的意见,但我似乎无法得到它的工作。我从csv读取的脚本看起来并不喜欢那条线。如果你不介意可以看看我的csript,让我知道它需要去哪里,或者如果我需要添加其他东西。我也不太确定如何将xnames配置为我想要的格式的日期。 – user7524882

+0

对不起,我不是很清楚。它看起来像DTG是代码中的日期和时间列表。在我的代码中,我的日期和时间列表位于名为xnames的变量中。我想如果你想改变你的日期,只需从DTG中创建一个新的列表,将每个元素修改为你想要的长度和你想要的格式。 xticks以rotateation = angle作为参数,这就是我沿着我的x轴旋转日期的方式。 xticks的第一个参数是标签的x值列表,第二个参数是标签列表。 –

+0

我编辑了我的答案。 Matplotlib有一些很好的内置日期格式,在此之前我不知道。 –