def gantt_chart(data, savename=None, show=False): """ Generate Gantt chart. :param data: something returned by :func:`gantt_values` function """ import matplotlib.pyplot as plt from matplotlib.colors import cnames colors_ = cnames.values() max = 0 i = 0 for robot in data.keys(): for start_index, stop_index, product in data[robot]: plt.hlines(robot, start_index, stop_index, label=product, lw=10, color=colors_[i]) if max < stop_index: max = stop_index i += 1 # add some styling plt.margins(0.1) plt.grid() plt.xticks(range(max + 2)) plt.yticks(range(len(data.keys()))) plt.legend() if savename: plt.savefig(savename) if show: plt.show() return True
def __init__(self, player, node, action="nothing", target=EmptyNode()): self.player = player self.node = node self.action = action self.target = target self.color = cnames.values()[player] self.id = None
def colorcheck(colname, varname): """ Local helper function performing sanity checks on Matplotlib color strings """ if not isinstance(colname, (str, unicode)): raise TypeError(varname + ' has to be a string!') if colname.lower() not in cnames.keys() and colname not in cnames.values(): msg = "Unsupported color `" + varname + " = " + colname + "`. Check `matplotlib.colors.cnames` for possible choices. " raise ValueError(msg)
def display_complete(Gs, degree=2): colors = list(cnames.values()) for G in Gs: color = random.choice(colors) qreds = divisors.full_classes(G, degree) todisp = [qred for qred in qreds if divisors.span(qreds[qred]) == len(G)] if len(todisp) == 0: continue N,M = get_dims(len(todisp)) fig, ax = plt.subplots(M,N) ax = np.array(ax).flatten() print(ax) for i, qred in enumerate(todisp): print(i, qred) divisor_view(G, qred, ax=ax[i], c=color)
def update_ownership(self, DEBUG=False): if DEBUG: print " UPDATING NODE OWNERSHIP" for p in self.players.values(): for n in p.nodes: if len(n.units) > 0 and n.owner != p.id: if DEBUG: print "Node %d removed from player %d" % (n.id, p.id) p.nodes.remove(n) n.color = cnames["white"] for p in self.players.values(): for u in p: # TODO: should be switched to a set union (make nodes hashable by # first) if u.node not in p.nodes: if DEBUG: print "Node %d added to player %d" % (u.node.id, p.id) p.nodes.append(u.node) u.node.color = cnames.values()[u.player] p.update_home()
def fun1(): fig, axes = plt.subplots(2, 2, facecolor='white', figsize=(16, 9)) fig.suptitle('Figure Subtitle', fontsize=20, fontweight='bold') fig.subplots_adjust(top=0.9, bottom=0.06, left=0.06, right=0.96) ax1, ax2 = axes[0, :] ax1.grid() ax1.set_title('Important dates in 2008-2009 financial crisis', size=16, color='k') array = np.random.randn(100).cumsum() # 绘制直线 ax1.plot(array, 'k--', linewidth=1, alpha=0.6, label='one') ax1.plot(array, 'b-', linewidth=1.3, drawstyle='steps-post', alpha=0.9, label='one') # 设置标签 ax1.text(0.99, 0.01, 'Stages', verticalalignment='bottom', horizontalalignment='right', transform=ax1.transAxes, color='k', fontsize=12, bbox={'facecolor': 'y', 'alpha': 0.2, 'pad': 1}) # X标注 ax1.set_xticks([0, 25, 50, 75, 100]) ax1.set_xticklabels(labels=['one', 'two', 'three', 'four', 'five'], rotation=30, fontsize='small') # ax.set_xlabel('Stages') ax1.set_ylabel('Values', bbox=dict(facecolor='y', pad=1, alpha=0.2), rotation='vertical') # xy轴长度 # ax.axis([xmin, xmax, ymin, ymax]) ax1.set_ylim([array.min() - 0.1 * (array.max() - array.min()), array.max() + 0.3 * (array.max() - array.min())]) ax1.set_xlim([-2, 102]) # 图注 ax1.legend(['dush', 'step'], loc='upper left', fontsize='x-small', shadow=True, ncol=1, framealpha=0.7) # 添加文字注解 minX = np.where(array.min() == array)[0][0] maxX = np.where(array.max() == array)[0][0] annotateData = [(minX, 'Min Value'), (maxX, 'Max Value')] for id, label in annotateData: ax1.annotate(label, xy=(id, array[id] + 0.2), xytext=(id, array[id] + 0.2 * (array.max() - array.min())), arrowprops=dict(facecolor='r', shrink=0.05), alpha=0.9, size=12, color='r') # subplot2 data = [[0.30, 0.15, 0.37, 0.27], [0.75, 0.52, 0.69, 0.36], [0.38, 0.67, 0.47, 0.63], [0.94, 0.18, 0.71, 0.64], [0.84, 0.90, 0.01, 0.65], [0.06, 0.59, 0.81, 0.06]] index = ['one', 'two', 'three', 'four', 'five', 'six'] columns = ['A', 'B', 'C', 'D'] colors = cnames.values() len_x = 15 # 坐标轴长度 len_space = 0.5 # 坐标轴首尾空白长度 len_inter = 1.0 # 不同组间隔 num_gp = len(data) # 数据组数 num_dt = len(data[0]) # 每组数据数 colors = random.sample(list(colors), num_dt) # 不同的颜色 width = (len_x - 2. * len_space - (num_gp - 1) * len_inter) / (num_dt * num_gp) fpos = len_space record = [] for i in range(num_gp): x = np.arange(fpos, fpos + width * num_dt, width)[:num_dt] ax2.bar(x, data[i], width=width, color=colors, alpha=0.5) record.append(x) fpos = x[-1] + len_inter # X标注 ax2.set_xticks(np.array(record).mean(axis=1)) ax2.set_xticklabels(labels=index, rotation=30, fontsize='small') # 添加legend patches = [mpatches.Patch(color=colors[i], label=col) for i, col in enumerate(columns)] ax2.legend(handles=patches, loc='upper left', fontsize='x-small', shadow=True, ncol=2, framealpha=0.7, title="Genus") # x = random.randn(500) # axes[0, 1].hist(x, color='r', bins=100, alpha=0.4) # 柱形图 # x = np.arange(50) # y = x + 10*random.rand(50) # axes[1, 0].scatter(x,y,alpha=0.8) # 散点图 plt.show()
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.db.models import F from django.urls import reverse from django.views import generic from .models import Question # dnck fun stuff: import time from django.utils import timezone from random import choice from matplotlib.colors import cnames hexcolors=list(cnames.values()) # # display a list of objects generic class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] # display a detail page for a particular type of object class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self):
def paintAll(ingraphs, spacing=1.4, painter=paint_multi): fig = plt.figure() if type(ingraphs) is dict: Gs, counts = zip(*ingraphs.items()) L = len(Gs) + 1 axes = plt.axes([0.01,0,0.85,1]) elif type(ingraphs) is list: Gs = ingraphs counts = None L = len(Gs) axes = plt.axes([0.01,0,0.98,1]) else: raise ValueError("expected list or dict, not "+str(type(ingraphs))) colors = list(cnames.values()) N,M = get_dims(L) if counts is not None: heatmap = np.zeros(get_dims(len(Gs))) heataxes = fig.add_axes([0.8,0.1,0.2,(0.2*N)/M]) heataxes.set_axis_off() offset = 0.02 colors = [random.choice(colors) for i in range(len(Gs))] for i,g in enumerate(Gs): y,x = i//M, i%M painter(g, axes, offset=spacing*np.array([x,N-y]), node_color=colors[i]) #, node_color=random.choice(colors) if counts is not None: heatmap[y,x] = counts[i] heataxes.text(x,y, counts[i], va='center', ha='center', color='black') heataxes.text(x-offset,y-offset, counts[i], va='center', ha='center', color='white') if counts is not None: heataxes.matshow(heatmap,cmap='Greys') # first is the place I want to be, second is the place I am top_pos = spacing*(N+1-min(N,M)) pos = [top_pos]*2 def scroll(mouse_event): pos[0] = min(top_pos, max(0, pos[0]+ 0.3*float(mouse_event.step))) def update(timer): if not plt.fignum_exists(fig.number): timer.stop() thistime = time.time() if ( abs(pos[0]-pos[1]) < 0.05 or not hasattr(update,'last_time')): update.last_time = thistime return dtime = thistime - update.last_time pos[1] += (pos[0]-pos[1])*(1-1.0/(1+dtime*7)) axes.axis([-0.1,M*spacing, pos[1], pos[1]+M*spacing]) fig.canvas.draw_idle() update.last_time = thistime timer = fig.canvas.new_timer(interval=20) timer.add_callback(update,timer) def start_timer(evt): timer.start() fig.canvas.mpl_disconnect(drawid) drawid = fig.canvas.mpl_connect('draw_event', start_timer) def pressed(mouse_event): x,y = int(mouse_event.xdata/spacing), N-int(mouse_event.ydata/spacing) idx = x+M*y if x >= 0 and x < M and y >= 0 and y < N and idx < len(Gs): plt.figure() CXT['select_G'] = Gs[idx] divisor_view(Gs[idx], index=idx, c=colors[idx]) fig.canvas.mpl_connect('scroll_event', scroll) fig.canvas.mpl_connect('button_press_event', pressed) axes.set_aspect('equal', 'datalim') axes.axis([-0.1,M*spacing, pos[0], pos[0]+M*spacing]) plt.show() paintAll.current_timer = timer # prevent GC in spyder