создание цветовой временной диаграммы с использованием цветовой шкалы и цветовых карт в Python - PullRequest
4 голосов
/ 25 июня 2011

Я пытаюсь создать график отслеживания времени на основе файла ежедневного отслеживания времени, который я использовал.Я написал код, который просматривает мои файлы и генерирует несколько списков.

endTimes - это список случаев, когда определенное действие заканчивается минутами, начиная с 0 в полночь первого дня месяца и заканчивая количеством минут в месяце.

метки - это список меток для времени, указанного в endTimes.Это на единицу меньше конечного времени, поскольку у трекеров нет данных до 0 минут.Большинство меток являются повторениями.

категорий содержит каждое уникальное значение меток в порядке того, насколько хорошо я считаю это время.

Я хочу создать цветную полосу или стек цветовых полос (1 для каждого дня)это изобразит, как я провожу свое время в течение месяца и нанесу цвет, связанный с каждой этикеткой.Каждое значение в категориях будет иметь связанный цвет.Больше синего для большего блага.Больше красного - больше плохого.Это уже для правильной цветовой карты струи, но мне нужно получить оскверненные значения цвета, равномерно распределенные для каждого значения в категориях.Затем я полагаю, что следующим шагом будет преобразование этого в перечисленную цветовую карту для использования для цветовой панели на основе того, как метки связаны с категориями.

Я думаю, что это правильный способ сделать это, но я не уверен.Я не уверен, как связать метки со значениями цвета.

Вот последняя часть моего кода на данный момент.Я нашел одну функцию для создания дискретных цветовых карт.Да, но это не то, что я ищу, и я не уверен, что происходит.

Спасибо за помощь!

# 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 голосов
/ 28 июня 2011

Звучит так, как будто вы хотите что-то наподобие гистограммы в виде столбца со значениями цвета, сопоставленными с заданным диапазоном?В этом случае вот пример:

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()

enter image description here

...