在图的右侧添加标签

时间:2015-10-14 02:19:54

标签: python matplotlib

我正在绘制时间序列数据。在这里,我想问一下如何在图的右侧添加标签。我的代码如下:

import pandas
import os
import datetime
import numpy as np
import glob

data_path = os.getcwd()


def convert_stamp_to_date(stamp):
    try:
        d = datetime.datetime.utcfromtimestamp(stamp)
    except:
        d = datetime.datetime.utcfromtimestamp(0)
    d = datetime.datetime(d.year, d.month, d.day, d.hour, d.minute, d.second)
    return d

#get data of 25 minutes
date1 = datetime.datetime(2014,7,20,7,0,0)
date2 = datetime.datetime(2014,7,20,7,25,0)

#load Activity data
activity_df = pandas.read_csv('%s/ITRCProject/oneP/activity.csv'%data_path, index_col=0)
activity_df['timestamp'] = activity_df['timestamp'].apply(convert_stamp_to_date)
activity_df = activity_df.drop_duplicates('timestamp')
condition1 = np.logical_and(activity_df['timestamp']>date1,activity_df['timestamp']<date2)
activity_df = activity_df[condition1]
activity_df.columns = ['timestamp', 'activity']

#load Call data
call_df = pandas.read_csv('%s/ITRCProject/oneP/Call.csv'%data_path, index_col=0)
call_df['timestamp'] = call_df['timestamp'].apply(convert_stamp_to_date)
call_df = call_df.drop_duplicates('timestamp')
condition2 = np.logical_and(call_df['timestamp']>date1,call_df['timestamp']<date2)
call_df = call_df[condition2]
call_df = call_df[call_df['types']==2]
call_df['types'] = 'Call_O'
call_df = call_df[['timestamp','types']]
call_df.columns = ['timestamp', 'activity']

#load SMS data
sms_df = pandas.read_csv('%s/ITRCProject/oneP/SMS.csv'%data_path, index_col=0)
sms_df['timestamp'] = sms_df['timestamp'].apply(convert_stamp_to_date)
sms_df = sms_df.drop_duplicates('timestamp')
condition3 = np.logical_and(sms_df['timestamp']>date1,sms_df['timestamp']<date2)
sms_df = sms_df[condition3]
sms_df = sms_df[(sms_df['types']==1)]
sms_df['types'] = 'SMS_Sent'
sms_df = sms_df[['timestamp','types']]
sms_df.columns = ['timestamp', 'activity']

#load Screen data
screen_df = pandas.read_csv('%s/ITRCProject/oneP/Screen.csv'%data_path, index_col=0)
screen_df['timestamp'] = screen_df['timestamp'].apply(convert_stamp_to_date)
screen_df = screen_df.drop_duplicates('timestamp')
condition4 = np.logical_and(screen_df['timestamp']>date1,screen_df['timestamp']<date2)
screen_df = screen_df[condition4]
screen_df = screen_df[screen_df['screenOn']==1]
screen_df['screenOn'] = 'Screen_On' 
screen_df.columns = ['timestamp', 'activity']

#load Charger data
charger_df = pandas.read_csv('%s/ITRCProject/oneP/BatteryProbe.csv'%data_path, index_col=0)
charger_df['timestamp'] = charger_df['timestamp'].apply(convert_stamp_to_date)
charger_df = charger_df.drop_duplicates('timestamp')
condition5 = np.logical_and(charger_df ['timestamp']>date1,charger_df ['timestamp']<date2)
charger_df  = charger_df[condition5]
charger_df = charger_df[(charger_df['status']==2)]
charger_df['status'] = 'charging'
charger_df = charger_df[['timestamp','status']]
charger_df.columns = ['timestamp', 'activity']

frames = [activity_df, charger_df, screen_df,sms_df,call_df]
result = pandas.concat(frames, ignore_index=True)

from matplotlib.ticker import FixedLocator
font = {'weight' : 'bold',
        'size'   : 35}
import matplotlib
matplotlib.rc('font', **font)
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as dates

%pylab inline

def colour(x):
    if 'none' in x:
        return '#ffaa33'
    elif 'high' in x:
        return '#3bb200'
    elif 'low' in x:
        return 'yellow'
    elif 'SMS_Sent' in x:
        return '#800080'
    elif 'Call_O' in x:
        return 'cyan'
    elif 'Screen_On' in x:
        return 'magenta'
    elif 'charging' in x:
        return '#3388ff'


def position(x):
    if 'none' in x:
        return 0
    elif 'high' in x:
        return 1
    elif 'low' in x:
        return 2
    elif 'SMS_Sent' in x:
        return 3
    elif 'Call_O' in x:
        return 4
    elif 'Screen_On' in x:
        return 5
    elif 'charging' in x:
        return 6


result['colour'] = result['activity'].apply(colour)
result['position'] = result['activity'].apply(position)
result = result.set_index('timestamp')
result.index.name = None
result= result.sort_index()
fig, ax = plt.subplots(figsize=(20,15))
ax.scatter(result.index, result.position, s=75, c=result.colour, marker='x')
ax.set_xlim([date1,date2])
ax.spines['top'].set_color('none') 
ax.xaxis.set_ticks_position('bottom')
ax.set_ylim(-1, 7)
ax.spines['right'].set_color('none')
ax.yaxis.set_ticks_position('left')
labels = ['NONE', 'HIGH','LOW','SENT_SMS','CALL_OUT','SCREEN_ON','CHARGING']
tick_locations = [0,1,2,3,4,5,6,7,8,9]
ax.yaxis.set_major_locator(FixedLocator(tick_locations))
ax.set_yticklabels(labels, minor=False)
plt.grid()
plt.show()

我的代码结果如下: enter image description here 所需的输出如下: enter image description here

1 个答案:

答案 0 :(得分:1)

您可以在图中的任何位置创建文本框。对于像这样的绘图标签,我会使用轴坐标来绘制相对于轴的文本。

以下示例与上面的布局类似(因为您没有提供数据,我无法完全复制图表):

fig, ax = plt.subplots(figsize=(8, 8))
ax.scatter(np.random.rand(100), np.random.rand(100),
           marker='+', c=np.random.rand(100),
           cmap='hsv')
ax.text(1.05, 0.5, "20 July 2014 07:00:00 - 20 July 2014 07:25:00",
        rotation=90, size=16, weight='bold',
        bbox=dict(edgecolor='lightgreen', facecolor='none', pad=10, linewidth=3),
        ha='left', va='center', transform=ax.transAxes)

结果如下:

enter image description here

如果您实际上不想要绿色框,则可以删除bbox参数。