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

发布于 2024-11-17 00:10:47 字数 4225 浏览 5 评论 0原文

我正在尝试根据我使用的每日时间跟踪文件制作时间跟踪图表。我编写了一些代码来爬行我的文件并生成一些列表。

endTimes 是特定活动结束的时间列表(以分钟为单位),从该月第一天午夜 0 点到该月的分钟数。

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

I'm trying to make a time tracking chart based on a daily time tracking file that I used. I wrote code that crawls through my files and generates a few lists.

endTimes is a list of times that a particular activity ends in minutes going from 0 at midnight the first day of the month to however many minutes are in a month.

labels is a list of labels for the times listed in endTimes. It is one shorter than endtimes since the trackers don't have any data about before 0 minute. Most labels are repeats.

categories contains every unique value of labels in order of how well I regard that time.

I want to create a colorbar or a stack of colorbars (1 for eachday) that will depict how I spend my time for a month and put a color associated with each label. Each value in categories will have a color associated. More blue for more good. More red for more bad. It is already in order for the jet colormap to be right, but I need to get desecrate color values evenly spaced out for each value in categories. Then I figure the next step would be to convert that to a listed colormap to use for the colorbar based on how the labels associated with the categories.

I think this is the right way to do it, but I am not sure. I am not sure how to associate the labels with color values.

Here is the last part of my code so far. I found one function to make a discrete colormaps. It does, but it isn't what I am looking for and I am not sure what is happening.

Thanks for the help!

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

耳根太软 2024-11-24 00:10:47

听起来您想要类似堆叠条形图的东西,其中颜色值映射到给定范围?在这种情况下,这是一个粗略的示例:

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

在此处输入图像描述

It sounds like you want something like a stacked bar chart with the color values mapped to a given range? In that case, here's a rough example:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文