在Python中使用色条和色图创建色彩编码的时间图表

4 投票
1 回答
2240 浏览
提问于 2025-04-16 20:15

我正在尝试制作一个时间追踪图表,基于我每天记录的时间文件。我写了一段代码,可以遍历我的文件并生成几个列表。

endTimes是一个列表,记录了某项活动结束的时间,以分钟为单位,从每个月的第一天午夜的0分钟开始,到这个月的总分钟数。

labels是一个与endTimes对应的标签列表,它比endTimes少一个,因为追踪器没有记录0分钟之前的数据。大多数标签都是重复的。

categories包含了所有独特的标签值,按照我对这些时间的评价顺序排列。

我想创建一个颜色条,或者一堆颜色条(每天一个),用来展示我一个月的时间花费情况,并为每个标签分配一种颜色。categories中的每个值都会有一个对应的颜色。颜色越蓝表示越好,颜色越红表示越差。现在这些颜色已经按照jet色图的顺序排列好了,但我需要为categories中的每个值均匀分配离散的颜色值。接下来,我想把这些颜色值转换成一个列表,以便根据与categories相关的标签来使用这个颜色条。

我觉得这样做是对的,但我不太确定。我不太清楚如何将标签与颜色值关联起来。

这是我目前代码的最后一部分。我找到一个函数可以生成离散的色图,它确实可以,但不是我想要的,我也不太明白发生了什么。

谢谢你的帮助!

# now I need to develop the graph
import numpy as np
from matplotlib import pyplot,mpl
import matplotlib
from  scipy import interpolate
from  scipy import *

def contains(thelist,name):
    # checks if the current list of categories contains the one just read                       
    for val in thelist:
        if val == name:
            return True
    return False

def getCategories(lastFile):
    '''
    must determine the colors to use
    I would like to make a gradient so that the better the task, the closer to blue
    bad labels will recieve colors closer to blue
    read the last file given for the information on how I feel the order should be
    then just keep them in the order of how good they are in the tracker
    use a color range and develop discrete values for each category by evenly spacing them out
    any time not found should assume to be sleep
    sleep should be white
    '''
    tracker = open(lastFile+'.txt') # open the last file
    # find all the categories
    categories = []
    for line in tracker:
         pos = line.find(':') # does it have a : or a ?
         if pos==-1: pos=line.find('?')
         if pos != -1: # ignore if no : or ?                        
             name = line[0:pos].strip() # split at the : or ?
             if contains(categories,name)==False: # if the category is new  
                 categories.append(name) # make a new one                
    return categories


# find good values in order of last day
newlabels=[]

for val in getCategories(lastDay):
    if contains(labels,val):
        newlabels.append(val)
categories=newlabels

# convert discrete colormap to listed colormap python
for ii,val in enumerate(labels):
    if contains(categories,val)==False:
        labels[ii]='sleep'

# create a figure
fig = pyplot.figure()
axes = []
for x in range(endTimes[-1]%(24*60)):
    ax = fig.add_axes([0.05, 0.65, 0.9, 0.15])
    axes.append(ax)


# figure out the colors to use
# stole this function to make a discrete colormap
# http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations

def cmap_discretize(cmap, N):
    """Return a discrete colormap from the continuous colormap cmap.

    cmap: colormap instance, eg. cm.jet. 
    N: Number of colors.

    Example
    x = resize(arange(100), (5,100))
    djet = cmap_discretize(cm.jet, 5)
    imshow(x, cmap=djet)
    """

    cdict = cmap._segmentdata.copy()
     # N colors
    colors_i = np.linspace(0,1.,N)
     # N+1 indices
    indices = np.linspace(0,1.,N+1)
    for key in ('red','green','blue'):
        # Find the N colors
        D = np.array(cdict[key])
        I = interpolate.interp1d(D[:,0], D[:,1])
        colors = I(colors_i)
         # Place these colors at the correct indices.
        A = zeros((N+1,3), float)
        A[:,0] = indices
        A[1:,1] = colors
        A[:-1,2] = colors
         # Create a tuple for the dictionary.
        L = []
        for l in A:
            L.append(tuple(l))
            cdict[key] = tuple(L)
     # Return colormap object.
    return matplotlib.colors.LinearSegmentedColormap('colormap',cdict,1024)

# jet colormap goes from blue to red (good to bad)    
cmap = cmap_discretize(mpl.cm.jet, len(categories))


cmap.set_over('0.25')
cmap.set_under('0.75')
#norm = mpl.colors.Normalize(endTimes,cmap.N)

print endTimes
print labels

# make a color list by matching labels to a picture

#norm = mpl.colors.ListedColormap(colorList)
cb1 = mpl.colorbar.ColorbarBase(axes[0],cmap=cmap
                   ,orientation='horizontal'
                   ,boundaries=endTimes
                   ,ticks=endTimes
                   ,spacing='proportional')

pyplot.show()

1 个回答

7

听起来你想要的是一种堆叠条形图,并且颜色值要对应到某个特定的范围?如果是这样的话,这里有一个简单的例子:

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

# Generate data....
intervals, weights = [], []
max_weight = 5
for _ in range(30):
    numtimes = np.random.randint(3, 15)
    times = np.random.randint(1, 24*60 - 1, numtimes)
        times = np.r_[0, times, 24*60]
    times.sort()
    intervals.append(np.diff(times) / 60.0)
    weights.append(max_weight * np.random.random(numtimes + 1))

# Plot the data as a stacked bar chart.
for i, (interval, weight) in enumerate(zip(intervals, weights)):
    # We need to calculate where the bottoms of the bars will be.
    bottoms = np.r_[0, np.cumsum(interval[:-1])]

    # We want the left edges to all be the same, but increase with each day.
    left = len(interval) * [i]
    patches = plt.bar(left, interval, bottom=bottoms, align='center')

    # And set the colors of each bar based on the weights
    for val, patch in zip(weight, patches):
        # We need to normalize the "weight" value between 0-1 to feed it into
        # a given colorbar to generate an actual color...
        color = cm.jet(float(val) / max_weight)
        patch.set_facecolor(color)

# Setting the ticks and labels manually...
plt.xticks(range(0, 30, 2), range(1, 31, 2))
plt.yticks(range(0, 24 + 4, 4), 
           ['12am', '4am', '8am', '12pm', '4pm', '8pm', '12am'])
plt.xlabel('Day')
plt.ylabel('Hour')
plt.axis('tight')
plt.show()

在这里输入图片描述

撰写回答