2017-08-17 58 views
-1

我想在两个月内每30分钟绘制一次电力消耗 我的代码正在工作我的问题是在xlabel中我不想有范围(1,2 .... 48 * 58) ,但我想有这样的一些东西1和48 * 30之间给予的塞康48 * 28给人月等名称之间一月NME ...在matplotlib中更改ylabel的名称

plt.xticks(rotation=70) 

    mask3 = (train['date'] >= '2008-01-01') & (train['date'] <= '2008-02-27') 
    week = train.loc[mask3] 
    plt.plot(range(48*58),week.LoadNette) 
    plt.ylabel("Electricy consumption") 
    plt.xlabel("Month") 
    plt.title('Electricity consumption/week') 

    plt.show() 

回答

1

通过搜索« python matplotlib在搜索引擎上使用日期作为xlabel»,你可以在Matplotlib文档中找到你想要的例子:https://matplotlib.org/examples/api/date_demo.html

这个例子假设你的xdata是日期,但现在情况并非如此。您需要创建日期的列表并使用的,而不是你的范围(48 * 58)名单,像这样:

import pandas 

xdata = pandas.date_range(
       pandas.to_datetime("2008-01-01"), 
       pandas.to_datetime("2008-02-27 23:30:00"), 
       freq=pandas.to_timedelta(30,unit="m")).tolist() 

这从开始时间的频率创建日期时间的列表,你的结束时间30分钟。

之后,您需要使用上面链接中的示例。在这里它被复制和调整了一下你的需求,但你需要玩弄它来适当地设置它。您可以在matplotlib中找到更多使用日期的示例,现在您将使用日期列表作为您的绘图的输入。

import datetime 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 
import matplotlib.cbook as cbook 

# define locators for every month and every day 
months = mdates.MonthLocator() # every month 
days = mdates.DayLocator() # every day 
monthsFmt = mdates.DateFormatter('%m') 

# create the plot and plot your data 
fig, ax = plt.subplots() 
ax.plot(xdata, week.LoadNette) 

# format the x ticks to have a major tick every month and a minor every day 
ax.xaxis.set_major_locator(months) 
ax.xaxis.set_major_formatter(monthsFmt) 
ax.xaxis.set_minor_locator(days) 

# format the xlabel to only show the month 
ax.format_xdata = mdates.DateFormatter('%m') 

# rotates and right aligns the x labels, and moves the bottom of the 
# axes up to make room for them 
fig.autofmt_xdate() 

plt.show() 

在Matplotlib使用日期很吓人,但它的不只是黑客你想这个特定的时间标签从长远来看更好。