def test_patheffect3(): p1, = plt.plot([1, 3, 5, 4, 3], 'o-b', lw=4) p1.set_path_effects([path_effects.SimpleLineShadow(), path_effects.Normal()]) plt.title( r'testing$^{123}$', path_effects=[path_effects.withStroke(linewidth=1, foreground="r")]) leg = plt.legend([p1], [r'Line 1$^2$'], fancybox=True, loc='upper left') leg.legendPatch.set_path_effects([path_effects.withSimplePatchShadow()]) text = plt.text(2, 3, 'Drop test', color='white', bbox={'boxstyle': 'circle,pad=0.1', 'color': 'red'}) pe = [path_effects.Stroke(linewidth=3.75, foreground='k'), path_effects.withSimplePatchShadow((6, -3), shadow_rgbFace='blue')] text.set_path_effects(pe) text.get_bbox_patch().set_path_effects(pe) pe = [path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx', facecolor='gray'), path_effects.PathPatchEffect(edgecolor='white', facecolor='black', lw=1.1)] t = plt.gcf().text(0.02, 0.1, 'Hatch shadow', fontsize=75, weight=1000, va='center') t.set_path_effects(pe)
def main(): fontsize = 18 plt.plot(data) title = "This is figure title" x_label = "This is x axis label" y_label = "This is y axis label" title_text_obj = plt.title(title, fontsize=fontsize, verticalalignment='bottom') title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()]) # offset_xy -- set the 'angle' of the shadow # shadow_rgbFace == set the color of the shadow # patch_alpha == setup the transparency of the shadow offset_xy = (1, -1) rgbRed = (1.0, 0.0, 0.0) alpha = 0.8 # customize shadow properties pe = patheffects.withSimplePatchShadow(shadow_rgbFace=rgbRed) # apply them to the xaxis anf yaxis labels xlabel_obj = plt.xlabel(x_label, fontsize=fontsize, alpha=0.5) xlabel_obj.set_path_effects([pe]) # ylabel_obj = plt.ylabel(y_label, fontsize=fontsize, alpha=0.5) ylabel_obj.set_path_effects([pe]) plt.show()
def plotEfficientFrontier(returns, tickers, numofsim=200, title='Simulated Efficient Frontier'): allocation = simAllocation(numofsim, tickers) port_returns = returns.dot(allocation) analytics = generateAnalytics(port_returns) rets = np.array(analytics.annual_return) / 100 vols = np.array(analytics.annual_volatility) / 100 sr = np.array(analytics.sharpe_ratio) # the charts fig8 = plt.figure(figsize=FIG_SIZE) plt.subplots_adjust(wspace=.5) plt.subplot() plt.scatter(vols, rets, c=sr, marker='o', cmap='coolwarm') plt.grid(True) plt.xlabel('annual volatility') plt.ylabel('annual return') plt.colorbar(label='Sharpe Ratio') title_text_obj = plt.title(title, fontsize=18, verticalalignment='bottom') title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()]) plt.show()
def path_effect(text='Sick Fermat'): fig = plt.figure(figsize=(8, 4)) t = fig.text(0.0, 0.0, text, fontsize=30) t = fig.text(0.1, 0.2, text, fontsize=30) t.set_path_effects([ PathPatchEffect(offset=(4, -4), hatch='xxxx', facecolor='gray'), PathPatchEffect(edgecolor='white', linewidth=1.1, facecolor='black') ]) t = fig.text(0.1, 0.5, text[::-1], fontsize=30, color='white') t.set_path_effects([ patheffects.Stroke(linewidth=3, foreground='black'), patheffects.Normal() ]) t = fig.text(0.1, 0.7, text[::-1], fontsize=30) t.set_path_effects([patheffects.withSimplePatchShadow()]) text_color = to_rgba('black') lines = [[[0, 1], [0.2, 0.2]], [[0, 1], [0.5, 0.5]], [[0, 1], [0.7, 0.7]], [[0.1, 0.1], [0, 1]]] for line in lines: fig.lines.append( Line2D(line[0], line[1], transform=fig.transFigure, figure=fig, color=text_color, linewidth=0.5)) return fig
def plotCorrelationMatrix(matrix, type=1, title=''): fig, ax = plt.subplots(figsize=FIG_SIZE) title_text_obj = ax.set_title(title, fontsize=18, verticalalignment='bottom') title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()]) if type == 1: sns.heatmap(matrix, annot=True, linewidths=.5) elif type == 2: sns.heatmap(matrix, annot=True, cmap="YlGnBu", linewidths=0.3, annot_kws={"size": 16}) else: sns.heatmap(matrix, annot=True, cmap='coolwarm', linewidths=0.3, annot_kws={"size": 16}) # Plot aesthetics plt.xticks(rotation=90) plt.yticks(rotation=0) b, t = plt.ylim() # discover the values for bottom and top # b += 0.5 # Add 0.5 to the bottom # t -= 0.5 # Subtract 0.5 from the top plt.ylim(b, t) # update the ylim(bottom, top) values plt.show()
def plot_heatmap(evaluators, store=True): mi_df = Evaluator.to_multi_index_frame(evaluators) detectors, datasets = mi_df.columns, mi_df.index fig, ax = plt.subplots(figsize=(len(detectors) + 2, len(datasets))) im = ax.imshow(mi_df, cmap=plt.get_cmap('YlOrRd'), vmin=0, vmax=1) plt.colorbar(im) # Show MultiIndex for ordinate Evaluator.insert_multi_index_yaxis(ax, mi_df) # Rotate the tick labels and set their alignment. ax.set_xticks(np.arange(len(detectors))) ax.set_xticklabels(detectors) plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode='anchor') # Loop over data dimensions and create text annotations. for i in range(len(detectors)): for j in range(len(datasets)): ax.text(i, j, f'{mi_df.iloc[j, i]:.2f}', ha='center', va='center', color='w', path_effects=[path_effects.withSimplePatchShadow( offset=(1, -1), shadow_rgbFace='b', alpha=0.9)]) ax.set_title('AUROC over all datasets and detectors') # Prevent bug where x axis ticks are completely outside of bounds (matplotlib/issues/5456) if len(datasets) > 2: fig.tight_layout() if store: evaluators[0].store(fig, 'heatmap', no_counters=True, store_in_figures=True) return fig
def plot_poly(axis, poly, shadow=True, **kw): if 'c' in kw: kw['color'] = kw['c'] del kw['c'] if shadow: kw['path_effects'] = [pfx.withSimplePatchShadow()] list(map(lambda p: axis.add_patch(PathPatch(pathify(p), **kw)), poly))
def plot_data(self, axis, x=[], shadow=True, **kw): x = self.data if not len(x) else x kw['markersize'] = kw['s'] if 's' in kw else 3 kw['zorder'] = kw['zorder'] if 'zorder' in kw else 2 if shadow: kw['path_effects'] = [pfx.withSimplePatchShadow()] axis.plot(self.data[:, 0], self.data[:, 1], 'o', **kw)
def plotConf(df_confusion,titulo,savefile): plt.ioff() fig = plt.figure() plt.clf() ax = fig.add_subplot(111) ax.set_aspect(1) res = ax.imshow(np.array(df_confusion), cmap=plt.cm.jet, interpolation='nearest') width, height = np.array(df_confusion).shape for x in xrange(width): for y in xrange(height): ax.annotate(str(df_confusion[x][y]), xy=(y, x), horizontalalignment='center', verticalalignment='center', color='white', fontweight='bold', path_effects=[path_effects.withSimplePatchShadow(alpha=0.5)]) plt.yticks( np.arange(height) ) plt.xticks( np.arange(width) ) plt.ylabel('Valor real') plt.xlabel('Valor predicho') cb = fig.colorbar(res) plt.title(titulo,fontsize=16) plt.savefig(savefile) return
def heatmap(df): """http://stackoverflow.com/questions/20520246/create-heatmap-using-pandas-timeseries""" dflen = len(df.index) dflen2 = len(df.columns) # print dflen, dflen2 fsize = (1.6 * dflen, .6 * dflen2) fig = plt.figure(figsize=fsize) ax = fig.add_subplot(111) # use dir(matplotlib.cm) to get a list of the installed colormaps # the "_r" means "reversed" and accounts for why zero values are plotted # as white cmap = CM.get_cmap('YlOrRd', 50) # http://matplotlib.org/examples/color/colormaps_reference.html ax.imshow(df, interpolation="nearest", cmap=cmap) # ax.invert_yaxis() # ax.xaxis.tick_top() v = df.columns.tolist() v2 = df.index.tolist() ax.set_xticks(np.arange(dflen) + 0., minor=False) ax.set_yticks(np.arange(dflen2) + 0., minor=False) ax.set_xticklabels(v) ax.set_yticklabels(v2) ax.grid(True) path_effects = [patheffects.withSimplePatchShadow(shadow_rgbFace=(1, 1, 1))] for i in range(dflen): for j in range(dflen2): ax.text(j, i, '{:.2f}'.format(df.iget_value(i, j)), size='medium', ha='center', va='center', path_effects=path_effects) plt.show()
def plot_coords(self, axis, v, shadow=True): color = cm.ScalarMappable(Normalize(v.min(), v.max()), cm.rainbow) kw = {'markersize' : 3} if shadow: kw['path_effects'] = [pfx.withSimplePatchShadow()] for c, (x, y) in zip(v, self.data): axis.plot(x, y, 'o', color=color.to_rgba(c), **kw)
def test_patheffect3(): ax3 = plt.subplot(111) p1, = ax3.plot([0, 1], [0, 1]) ax3.set_title(r'testing$^{123}$', path_effects=[withStroke(linewidth=1, foreground="r")]) leg = ax3.legend([p1], [r'Line 1$^2$'], fancybox=True, loc=2) leg.legendPatch.set_path_effects([withSimplePatchShadow()])
def set_circle(self,x,y,r,c): self.x = x self.y = y self.circle = mpatches.Circle((x,y), r, fc=c, ec=(0.1, 0.1, 0.1)) self.circle.set_linestyle('solid') self.circle.set_linewidth(2.0) try: self.circle.set_path_effects([path_effects.withSimplePatchShadow()]) except: pass
def plot_triangle(self, axis, s, shadow=True, **kw): p = self.data[list(s)] if 'c' in kw: kw['color'] = kw['c'] del kw['c'] kw['color'] = 'black' if not 'color' in kw else kw['color'] kw['alpha'] = 0.1 if not 'alpha' in kw else kw['alpha'] kw['zorder'] = 0 if not 'zorder' in kw else kw['zorder'] if shadow: kw['path_effects'] = [pfx.withSimplePatchShadow()] return axis.add_patch(Polygon(p, **kw))
def plot_vertex(self, axis, s, shadow=True, **kw): p = self.data[list(s)] if 'color' in kw: kw['c'] = kw['color'] del kw['color'] kw['c'] = 'black' if not 'c' in kw else kw['c'] kw['alpha'] = 1 if not 'alpha' in kw else kw['alpha'] kw['zorder'] = 2 if not 'zorder' in kw else kw['zorder'] kw['markersize'] = 1 if not 'markersize' in kw else kw['markersize'] if shadow: kw['path_effects'] = [pfx.withSimplePatchShadow()] return axis.plot(p[:,0], p[:,1], 'o', **kw)
def __init__(self, ax, x1, x2, y, height, gradient=True, tip=0.0025, color="k", shadow=False, **kwargs): super(GeneGlyph, self).__init__(ax) # Figure out the polygon vertices first orientation = 1 if x1 < x2 else -1 level = 10 tip = min(tip, abs(x1 - x2)) # Frame p1 = (x1, y - height * 0.5) p2 = (x2 - orientation * tip, y - height * 0.5) p3 = (x2, y) p4 = (x2 - orientation * tip, y + height * 0.5) p5 = (x1, y + 0.5 * height) if "fc" not in kwargs: kwargs["fc"] = color if "ec" not in kwargs: kwargs["ec"] = color P = Polygon([p1, p2, p3, p4, p5], **kwargs) self.append(P) if gradient: zz = kwargs.get("zorder", 1) zz += 1 # Patch (apply white mask) for cascade in np.arange(0, 0.5, 0.5 / level): p1 = (x1, y - height * cascade) p2 = (x2 - orientation * tip, y - height * cascade) p3 = (x2, y) p4 = (x2 - orientation * tip, y + height * cascade) p5 = (x1, y + height * cascade) self.append( Polygon([p1, p2, p3, p4, p5], fc="w", lw=0, alpha=0.2, zorder=zz)) if shadow: import matplotlib.patheffects as pe P.set_path_effects([pe.withSimplePatchShadow((1, -1), alpha=0.4)]) self.add_patches()
def dr_cmap(fx,ftg9): cm8 = pd.read_csv('dat\\cor_maps.csv',encoding='gbk') df2 = mx_sum_main(fx) df2.to_csv("tmp\\mx_"+ftg9+'.csv',encode='utf8'); for xss in cm8['name']: df2.plot(kind='bar',colormap=xss,rot=0,figsize=(20,5) ,path_effects=[path_effects.withSimplePatchShadow()]); plt.axhline(50, color='r'); plt.legend(ncol=3,loc=2) plt.tight_layout() fss="tmp\\m1cor_"+xss+"_"+ftg9+".png";plt.savefig(fss); plt.show();print(xss,",",fss)
def test_patheffect3(): p1, = plt.plot([1, 3, 5, 4, 3], "o-b", lw=4) p1.set_path_effects([path_effects.SimpleLineShadow(), path_effects.Normal()]) plt.title(r"testing$^{123}$", path_effects=[path_effects.withStroke(linewidth=1, foreground="r")]) leg = plt.legend([p1], [r"Line 1$^2$"], fancybox=True, loc=2) leg.legendPatch.set_path_effects([path_effects.withSimplePatchShadow()]) text = plt.text(2, 3, "Drop test", color="white", bbox={"boxstyle": "circle,pad=0.1", "color": "red"}) pe = [ path_effects.Stroke(linewidth=3.75, foreground="k"), path_effects.withSimplePatchShadow((6, -3), shadow_rgbFace="blue"), ] text.set_path_effects(pe) text.get_bbox_patch().set_path_effects(pe) pe = [ path_effects.PathPatchEffect(offset=(4, -4), hatch="xxxx", facecolor="gray"), path_effects.PathPatchEffect(edgecolor="white", facecolor="black", lw=1.1), ] t = plt.gcf().text(0.02, 0.1, "Hatch shadow", fontsize=75, weight=1000, va="center") t.set_path_effects(pe)
def plotCorrelationMatrixWithCluster(matrix, title=''): fig = sns.clustermap(matrix, row_cluster=True, col_cluster=True, figsize=(10, 10)) title_text_obj = plt.title(title, fontsize=18, verticalalignment='bottom') title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()]) plt.setp(fig.ax_heatmap.xaxis.get_majorticklabels(), rotation=90) plt.setp(fig.ax_heatmap.yaxis.get_majorticklabels(), rotation=0) plt.show()
def test_patheffect3(): p1, = plt.plot([1, 3, 5, 4, 3], 'o-b', lw=4) p1.set_path_effects([path_effects.SimpleLineShadow(), path_effects.Normal()]) plt.title(r'testing$^{123}$', path_effects=[path_effects.withStroke(linewidth=1, foreground="r")]) leg = plt.legend([p1], [r'Line 1$^2$'], fancybox=True, loc=2) leg.legendPatch.set_path_effects([path_effects.withSimplePatchShadow()]) text = plt.text(2, 3, 'Drop test', color='white', bbox={'boxstyle': 'circle,pad=0.1', 'color': 'red'}) pe = [path_effects.Stroke(linewidth=3.75, foreground='k'), path_effects.withSimplePatchShadow((6, -3), shadow_rgbFace='blue')] text.set_path_effects(pe) text.get_bbox_patch().set_path_effects(pe) pe = [path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx', facecolor='gray'), path_effects.PathPatchEffect(edgecolor='white', facecolor='black', lw=1.1)] t = plt.gcf().text(0.02, 0.1, 'Hatch shadow', fontsize=75, weight=1000, va='center') t.set_path_effects(pe)
def _place_labels(self, labels, colors): for label in self.labels: label.remove() del self.labels[:] self.rows = [[]] renderer = self.canvas.get_renderer() todata = self.ax.transData.inverted() xmargin, ymargin = todata.transform((self.margin, self.margin)) x, y = xmargin, ymargin # Let the labels flow from left to right, wrapping around for label_index in range(len(labels)): s = labels[label_index] label = Text(x, y, s, verticalalignment='top', bbox=dict(facecolor=colors[label_index], edgecolor='w', pad=self.pad)) # I could not see the dark text on some backgrounds label.set_path_effects([ PathEffects.withSimplePatchShadow(offset=(1,-1), shadow_rgbFace=(1., 1.,0.5)), ]) label = self.ax.add_artist(label) # Keep both a master list of labels, and a list of labelson each row self.labels.append(label) self.rows[-1].append(label) # I have to render the label once in order to determine its actual size label.draw(renderer) bbox = label.get_bbox_patch().get_window_extent(renderer).transformed(todata) if (x + bbox.width) > 1: x = xmargin y -= bbox.height label.set_position((x, y)) self.rows.append([self.rows[-1].pop()]) x += bbox.width # After some tinkering, I am centering the labels in the axis bbox = self._get_labels_bbox() labels_center = bbox.corners().mean(0) view_center = self.ax.viewLim.corners().mean(0) for label in self.labels: x, y = label.get_position() + (view_center - labels_center) label.set_position((x, y))
def generate_combinations_img(class_names, class_names_bak, p_matrix, title, fname='overlaps_img'): a_size = len(p_matrix) diff = np.zeros([a_size, a_size]) for i in xrange(a_size): for j in xrange(a_size): if i == j: pass else: _sum = p_matrix[i][i] + p_matrix[j][j] comb = p_matrix[i][j] diff[i][j] = float(comb)/float(_sum) fig = plt.figure(figsize=(16, 9)) ax = fig.add_subplot(111) diffa = masked_array(diff, diff != 0) diffb = masked_array(diff, diff == 0) cax = ax.imshow(diffb, cmap=cm.winter, interpolation='None', origin='lower', aspect='auto') cba = plt.colorbar(cax, format='%.1f') caxb = ax.imshow(diffa, cmap=cm.Reds, interpolation='None', origin='lower', aspect='auto') plt.xticks(range(a_size)) ax.set_xticklabels(class_names_bak) plt.xticks(rotation=80) plt.yticks(range(a_size)) ax.set_yticklabels(class_names_bak) for i in xrange(a_size): for j in xrange(a_size): ax.text(j, i, '{0}/{1:.2f}'.format(p_matrix[i][j], diff[i][j]), size='medium', ha='center', va='center', path_effects=[patheffects.withSimplePatchShadow(shadow_rgbFace=(1, 1, 1))]) plt.title(title) # bar = fig.colorbar(cax, format='%.1f') plt.rc('text', usetex=True) cba.set_label('$\\frac{a_{i,j}}{a_{i,i}+a_{j,j}}$', fontsize=25, rotation=0, labelpad=40) plt.savefig(folder+'/'+fname, bbox_inches='tight', transparent=False) plt.close()
def plotTimeSeries(series, title='', xlabel='', ylabel='', tickermap=''): ax = series.plot(figsize=FIG_SIZE, fontsize=12, linewidth=3, linestyle='-') ax.set_xlabel(xlabel, fontsize=16) ax.set_ylabel(ylabel, fontsize=16) title_text_obj = ax.set_title(title, fontsize=18, verticalalignment='bottom') title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()]) # pe = patheffects.withSimplePatchShadow(offset = (1, -1), shadow_rgbFace = (1,0,0), calpha = 0.8) names = series.columns if tickermap: names = names.map(tickermap) ax.legend(names, fontsize=16) plt.show()
def compareDistribution(series, tickers, title='', tickermap={}): fig, ax = plt.subplots(figsize=FIG_SIZE) title_text_obj = ax.set_title(title, fontsize=18, verticalalignment='bottom') title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()]) for ticker in tickers: sns.distplot(series[ticker]) names = series.columns if tickermap: names = names.map(tickermap) ax.legend(names, fontsize=12) ax.set_xlabel('Returns Distribution', fontsize=14) ax.set_ylabel('Frequency', fontsize=14) plt.show()
def plotCountry(m, ax, id, path='gadm0'): country, lonlat = merged[id] r = shapefile.Reader(r"%s/%s_adm0" % (path, country)) shapes = r.shapes() records = r.records() for record, shape in zip(records, shapes): lons, lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [ data, ] else: segs = [] for i in range(1, len(shape.parts)): index = shape.parts[i - 1] index2 = shape.parts[i] segs.append(data[index:index2]) segs.append(data[index2:]) lines = LineCollection(segs, antialiaseds=(1, )) lines.set_facecolors('lightgreen') lines.set_edgecolors('k') lines.set_linewidth(0.1) lines.set_alpha(0.5) ax.add_collection(lines) # Add country centroid lon, lat = lonlat xpt, ypt = m(lon, lat) txt = ax.annotate(id, (xpt, ypt), color='r', size='medium', ha='center', va='center', path_effects=[ PathEffects.withStroke(linewidth=3, foreground="w"), PathEffects.withSimplePatchShadow() ])
def __init__(self, ax, x1, x2, y, height, gradient=True, tip=.0025, \ color="k", shadow=False, **kwargs): super(GeneGlyph, self).__init__(ax) # Figure out the polygon vertices first orientation = 1 if x1 < x2 else -1 level = 10 tip = min(tip, abs(x1 - x2)) # Frame p1 = (x1, y - height * .5) p2 = (x2 - orientation * tip, y - height * .5) p3 = (x2, y) p4 = (x2 - orientation * tip, y + height * .5) p5 = (x1, y + .5*height) if "fc" not in kwargs: kwargs["fc"] = color if "ec" not in kwargs: kwargs["ec"] = color P = Polygon([p1, p2, p3, p4, p5], **kwargs) self.append(P) if gradient: zz = kwargs.get("zorder", 1) zz += 1 # Patch (apply white mask) for cascade in np.arange(0, .5, .5 / level): p1 = (x1, y - height * cascade) p2 = (x2 - orientation * tip, y - height * cascade) p3 = (x2, y) p4 = (x2 - orientation * tip, y + height * cascade) p5 = (x1, y + height * cascade) self.append(Polygon([p1, p2, p3, p4, p5], fc='w', \ lw=0, alpha=.2, zorder=zz)) if shadow: import matplotlib.patheffects as pe P.set_path_effects([pe.withSimplePatchShadow((1, -1), \ alpha=.4, patch_alpha=1)]) self.add_patches()
def plotReturnDistribution(returns, ticker, binsize=35, title=''): fig, ax = plt.subplots(figsize=FIG_SIZE) ax.hist(returns[ticker], bins=binsize, color='steelblue', density=True, alpha=0.5, histtype='stepfilled', edgecolor='red') title_text_obj = ax.set_title(title, fontsize=18, verticalalignment='bottom') title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()]) sigma, mu = returns[ticker].std(), returns[ticker].mean( ) # mean and standard deviation s = np.random.normal(mu, sigma, 1000) count, bins, ignored = ax.hist(s, binsize, density=True, alpha=0.1) ax.plot(bins, 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(bins - mu)**2 / (2 * sigma**2)), linewidth=1.5, color='r') ax.annotate('Skewness: {}\n\nKurtosis: {}'.format( round(returns[ticker].skew(), 2), round(returns[ticker].kurtosis(), 2)), xy=(10, 20), xycoords='axes points', xytext=(20, 360), fontsize=14) ax.set_xlabel('Values') ax.set_ylabel('Frequency') plt.show()
def plot_correlations(features_df, author_comments=0, ax=None, is_filtered=False): if ax is None: fig, ax = plt.subplots(1, 1, figsize=(14, 12)) else: fig = ax.get_figure() labels = list(features_df.columns) corr = features_df[features_df['author_comments'] > author_comments].corr() cax = ax.matshow(corr, vmin=-1, vmax=1, cmap=plt.get_cmap("jet")) cbar = plt.colorbar(cax, ax=ax, fraction=0.046, pad=0.04) ax.set_xticklabels([' '] + labels, rotation=45, ha='left') ax.set_yticklabels([' '] + labels) ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) if is_filtered: ax.set_title( rf'Filtered Comment Correlations ($comments_{{author}} \geq {author_comments}$)', y=1.15) else: ax.set_title( rf'Comment Correlations ($comments_{{author}} \geq {author_comments}$)', y=1.15) for i in range(corr.shape[0]): for j in range(corr.shape[1]): ax.text(i, j, f'{corr.iloc[j, i]:.2f}', ha="center", va="center", color="b", path_effects=[ path_effects.withSimplePatchShadow(offset=(1, -1), shadow_rgbFace="w", alpha=0.9) ]) return fig, ax
def heatmap(df): """http://stackoverflow.com/questions/20520246/create-heatmap-using-pandas-timeseries""" dflen = len(df.index) dflen2 = len(df.columns) # print dflen, dflen2 fsize = (1.6 * dflen, .6 * dflen2) fig = plt.figure(figsize=fsize) ax = fig.add_subplot(111) # use dir(matplotlib.cm) to get a list of the installed colormaps # the "_r" means "reversed" and accounts for why zero values are plotted # as white cmap = CM.get_cmap('YlOrRd', 50) # http://matplotlib.org/examples/color/colormaps_reference.html ax.imshow(df, interpolation="nearest", cmap=cmap) # ax.invert_yaxis() # ax.xaxis.tick_top() v = df.columns.tolist() v2 = df.index.tolist() ax.set_xticks(np.arange(dflen) + 0., minor=False) ax.set_yticks(np.arange(dflen2) + 0., minor=False) ax.set_xticklabels(v) ax.set_yticklabels(v2) ax.grid(True) path_effects = [ patheffects.withSimplePatchShadow(shadow_rgbFace=(1, 1, 1)) ] for i in range(dflen): for j in range(dflen2): ax.text(j, i, '{:.2f}'.format(df.iget_value(i, j)), size='medium', ha='center', va='center', path_effects=path_effects) plt.show()
def test_patheffect3(): ax3 = plt.subplot(111) p1, = ax3.plot([0, 1], [0, 1]) leg = ax3.legend([p1], ["Line 1"], fancybox=True, loc=2) leg.legendPatch.set_path_effects([withSimplePatchShadow()])
def make_plot(channel, time, drawLabels=True): #get the log file directory = "logs/" + channel + '/' + time filename = 'rate.csv' file_path = os.path.relpath(directory + '/' + filename) with open(file_path, 'r') as rate: rates = map(lambda x: x.strip(), list(rate)) start_hour = int(rates[0].split('=')[1].split('_')[0]) start_min = int(rates[0].split('=')[1].split('_')[1]) #Load data rates = rates[1:] events = [] to_delete = [] for rate in rates: if len(rate.split('*')) >= 3: events.append((int(rate.split('*')[1]), rate.split(',', 1)[1])) to_delete.append(rate) rates = [x for x in rates if x not in to_delete] old_len = len(rates) rates = remove_trailing_zeroes(rates) num_removed = old_len - len(rates) mins = map( lambda x: int( filter(lambda x: x in string.printable, x).split(',')[0]), rates) ##### XXX l = len(mins) mins = [] for i in range(l): mins.append(i) ##### XXX y_data = map(lambda x: float(x.split(',')[1]), rates) show_viewers = False try: y_data2 = map(lambda x: int(x.split(',')[2]), rates) show_viewers = True except IndexError: print rates pass dur = mins[-1] + 1 #in minutes #interval = 15 interval = get_xinterval(dur) padding_mins = start_min % interval carry = start_min / interval x_data = range(carry * interval, start_min + dur + min(num_removed, padding_mins)) x = np.array(x_data) y = np.random.randint(1, size=padding_mins) #pad it with all 0's y = np.append(y, np.array(y_data)) y = np.append(y, np.random.randint(1, size=min( num_removed, padding_mins))) #potentially add zeroes to the end if show_viewers: y2 = np.random.randint(1, size=padding_mins) #pad it with all 0's y2 = np.append(y2, np.array(y_data2)) y2 = np.append( y2, np.random.randint( 1, size=min(num_removed, padding_mins))) #potentially add zeroes to the end #print len(x) #print len(y) #print len(y2) times = time.split('-') #2014-08-23-04AM try: year = int(times[0]) mo = int(times[1]) day = int(times[2]) hour = start_hour minute = start_min minute = 0 #????????????????????????????????????????????????????????????? start_time = datetime.datetime(year, mo, day, hour, minute, 0) except ValueError: #debugging. print "THIS SHOULD NEVER HAPPEN! Email me [email protected] right away!" start_time = datetime.datetime(2014, 8, 11, start_hour, start_min) #Removes leading zeroes from all the "words" in s. #"00138 hello 01AM" -> "138 hello 1AM" def removeLeadingZeroes(s): return " ".join(map(lambda x: x.lstrip('0'), s.split(" "))) def formatTime(x, pos): #timestamp = (start_time - datetime.datetime(1970, 1, 1)).total_seconds() + x*60 #now_time = datetime.datetime.fromtimestamp(timestamp) #does not convert time zones. Need time zones. now_time = datetime.timedelta(hours=float(x) / 60) + start_time if dur > 2160: #Aug 5, 8AM return removeLeadingZeroes(now_time.strftime("%b %d, %I %p")) elif interval >= 60: #8AM return removeLeadingZeroes(now_time.strftime("%I %p")) else: #7:45 AM return removeLeadingZeroes(now_time.strftime("%I:%M %p")) print "Drawing rate over time graph..." #START GRAPHING #plt.figure(num=None, figsize=(36, 16), dpi=80) plt.figure(num=None, figsize=(27, 12), dpi=80) #fig, ax = plt.subplots() ax = plt.axes() ax.xaxis.grid(True) ax.xaxis.set_major_formatter(FuncFormatter(formatTime)) ax.yaxis.grid(True) ax.grid(True) r = 45 if dur >= 2160: r = 270 plt.xticks(np.arange(min(x), max(x) + 1, interval), rotation=r) months = [ '', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] try: i = int(times[1]) mon = months[i] ye = int(times[2]) da = int(times[0]) plt.title("%s - %s %d, %d\n" % (channel, mon, ye, da)) except (ValueError, IndexError): plt.title(channel + '\n') settingsDict = getSettings() local_timezone = None try: local_timezone = settingsDict['timezone'] except KeyError as e: print "Setting missing:", e raise except ValueError as e: print "Malformed setting:", e raise if local_timezone.lower().strip() == 'none' or local_timezone.lower( ).strip() == 'auto': local_timezone = datetime.datetime.now( tzlocal()).tzname() #Eastern Daylight Time else: local_timezone = local_timezone.strip() split = local_timezone.split(" ") if len(split) > 1: local_timezone = "".join([word[0] for word in split]) avg_mpm = np.mean(y) plt.xlabel('\nTimes in ' + local_timezone) plt.ylabel('\nMessages per minute (Avg=%0.2f)\n' % avg_mpm, color='blue') for tl in ax.get_yticklabels(): tl.set_color('blue') plt.plot(x, y, linewidth=2, color='#4422AA') if show_viewers: ax2color = 'green' ax2 = ax.twinx() ax2.plot(x, y2, linewidth=4, color=ax2color) ax2.fill_between(x, 0, y2, color=ax2color, alpha=0.1) ax2.set_frame_on(True) ax2.patch.set_visible(False) ax2.yaxis.set_ticks_position('right') ax2.yaxis.set_label_position('right') avg_viewercount = np.mean(y2) ax2.set_ylabel('Viewercount (Avg=%0.1f)\n\n' % avg_viewercount, color=ax2color, labelpad=50, rotation=270) m = 1.16 * max(y) m2 = 1.16 * max(y2) ax.set_yticks(np.arange(0, m, get_yinterval(max(y)))) ax2.set_yticks(np.arange(0, m2, get_yinterval(max(y2)))) ax.set_ylim(0, m) ax2.set_ylim(0, m2) for tl in ax2.get_yticklabels(): tl.set_color(ax2color) ax.fill_between(x, 0, y, color='#5577DD') font = {'size': 25} rc('font', **font) ticklist = ax2.get_yticks() height_diff = ticklist[1] - ticklist[0] height_offset = ticklist[1] init_offset = height_offset ha = 'center' for event in events: if drawLabels: plt.axvline(x=event[0] + padding_mins + carry * interval, color='red', linewidth=2, label=event[1]) s = event[1].replace('\\n', '\n') down = ax2.yaxis.get_view_interval()[1] - height_offset plt.text( event[0] + padding_mins + carry * interval, down, s, color='red', verticalalignment='top', horizontalalignment=ha, fontsize=25, rotation=0, #rotation=270, path_effects=[PathEffects.withSimplePatchShadow(linewidth=2)]) #path_effects=[PathEffects.withStroke(linewidth=1,foreground="black")]) height_offset = ( height_offset + height_diff) if height_offset == init_offset else init_offset #height_offset = height_diff - height_offset #S E L L O U T plt.text(0.01, 0.99, 'github.com/popcorncolonel/chat_stats', color='#666666', verticalalignment='top', horizontalalignment='left', fontsize=25, rotation=0, transform=ax.transAxes) plt.text(0.99, 0.99, 'http://twitch.tv/' + channel, color='#666666', verticalalignment='top', horizontalalignment='right', fontsize=25, rotation=0, transform=ax.transAxes) #plt.text(-0.05, -0.170, 'http://github.com/popcorncolonel/chat_stats', color='grey', verticalalignment='top', # horizontalalignment='left', fontsize=25, rotation=0, transform=ax.transAxes) #plt.text(1.05, -0.170, 'http://www.twitch.tv/'+channel, color='grey', verticalalignment='top', # horizontalalignment='right', fontsize=25, rotation=0, transform=ax.transAxes) #plt.show() #for running locally rather than saving the figure directory = "images/" + channel + '/' + time if not os.path.exists(directory): os.makedirs(directory) plt.savefig(directory + '/rate.png', bbox_inches='tight') print "Rate graph completed!"
import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects fig = plt.figure(figsize=(5, 1.5)) text = fig.text(0.5, 0.5, 'Hello path effects world!\nThis is the normal ' 'path effect.\nPretty dull, huh?', ha='center', va='center', size=20) text.set_path_effects([path_effects.Normal()]) plt.show() text = plt.text(0.5, 0.5, 'Hello path effects world!', path_effects=[path_effects.withSimplePatchShadow()]) plt.plot([0, 3, 2, 5], linewidth=5, color='blue', path_effects=[path_effects.SimpleLineShadow(), path_effects.Normal()]) plt.show()
path_effects=[PathEffects.withStroke(linewidth=3, foreground="w")]) txt.arrow_patch.set_path_effects([ PathEffects.Stroke(linewidth=5, foreground="w"), PathEffects.Normal() ]) pe = [PathEffects.withStroke(linewidth=3, foreground="w")] ax1.grid(True, linestyle="-", path_effects=pe) ax2 = plt.subplot(132) arr = np.arange(25).reshape((5, 5)) ax2.imshow(arr) cntr = ax2.contour(arr, colors="k") plt.setp( cntr.collections, path_effects=[PathEffects.withStroke(linewidth=3, foreground="w")]) clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True) plt.setp( clbls, path_effects=[PathEffects.withStroke(linewidth=3, foreground="w")]) # shadow as a path effect ax3 = plt.subplot(133) p1, = ax3.plot([0, 1], [0, 1]) leg = ax3.legend([p1], ["Line 1"], fancybox=True, loc=2) leg.legendPatch.set_path_effects([PathEffects.withSimplePatchShadow()]) plt.show()
x = np.linspace(0.5, 3.5, 100) y = np.sin(x) fontsize = 23 # plot a sin(x) func plt.plot(x, y, ls="--", lw=2) # set text contents title = "$y=\sin({x})$" xaxis_label = "$x\_axis$" yaxis_label = "$y\_axis$" # get text instance title_text_obj = plt.title(title, fontsize=fontsize, va="bottom") xaxis_label_text_obj = plt.xlabel(xaxis_label, fontsize=fontsize - 3, alpha=1.0) yaxis_label_text_obj = plt.ylabel(yaxis_label, fontsize=fontsize - 3, alpha=1.0) # set shadow title_text_obj.set_path_effects([pes.withSimplePatchShadow()]) pe = pes.withSimplePatchShadow(offset=(1, -1), shadow_rgbFace="r", alpha=.3) xaxis_label_text_obj.set_path_effects([pe]) yaxis_label_text_obj.set_path_effects([pe]) plt.show()
def Spectrum(pol, long, darkmode, png, foregrounds, masks, nside): params = { 'savefig.dpi': 300, # save figures to 300 dpi 'xtick.top': False, 'ytick.right': True, #Set to false 'axes.spines.top': True, #Set to false 'axes.spines.bottom': True, 'axes.spines.left': True, 'axes.spines.right': True, #Set to false@ 'axes.grid.axis': 'y', 'axes.grid': False, 'ytick.major.size': 10, 'ytick.minor.size': 5, 'xtick.major.size': 10, 'xtick.minor.size': 5, 'ytick.major.width': 1.5, 'ytick.minor.width': 1.5, 'xtick.major.width': 1.5, 'xtick.minor.width': 1.5, 'axes.linewidth': 1.5, 'axes.prop_cycle': cycler(color=[ '#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A', '#19D3F3', '#FF6692', '#B6E880', '#FF97FF', '#FECB52' ]) #'ytick.major.size' : 6, #'ytick.minor.size' : 3, #'xtick.major.size' : 6, #'xtick.minor.size' : 3, } blue, red, green, purple, orange, teal, lightred, lightgreen, pink, yellow = ( "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", ) black = 'k' if darkmode: rcParams['text.color'] = 'white' # axes background color rcParams['axes.facecolor'] = 'white' # axes background color rcParams['axes.edgecolor'] = 'white' # axes edge color rcParams['axes.labelcolor'] = 'white' rcParams['xtick.color'] = 'white' # color of the tick labels rcParams['ytick.color'] = 'white' # color of the tick labels rcParams['grid.color'] = 'white' # grid color rcParams[ 'legend.facecolor'] = 'inherit' # legend background color (when 'inherit' uses axes.facecolor) rcParams[ 'legend.edgecolor'] = 'white' # legend edge color (when 'inherit' uses axes.edgecolor) black = 'white' rcParams.update(params) # ---- Figure parameters ---- if pol: ymin, ymax = (1e-3, 2e2) if long: xmin, xmax = (1, 3000) ymax15, ymax2 = (ymax + 100, 1e7) else: xmin, xmax = (10, 1000) else: ymin, ymax = (0.05, 7e2) if long: xmin, xmax = (0.3, 4000) ymax15, ymax2 = (ymax + 500, 1e7) else: xmin, xmax = (10, 1000) if long: # Figure ratio = 5 w, h = (16, 8) fig, (ax2, ax) = plt.subplots(2, 1, sharex=True, figsize=(w, h), gridspec_kw={'height_ratios': [1, ratio]}) aspect_ratio = w / h * 1.25 # Correct for ratio rotdir = -1 ax2.spines['bottom'].set_visible(False) ax.spines['top'].set_visible(False) ax2.tick_params(labelbottom=False) ax2.xaxis.set_ticks_position('none') # ---- Adding broken axis lines ---- d = .005 # how big to make the diagonal lines in axes coordinates kwargs = dict(transform=ax2.transAxes, color=black, clip_on=False) ax2.plot((-d, +d), (-d * ratio, +d * ratio), **kwargs) # top-left diagonal ax2.plot((1 - d, 1 + d), (-d * ratio, +d * ratio), **kwargs) # top-right diagonal kwargs.update(transform=ax.transAxes) # switch to the bottom axes ax.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal ax.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) # bottom-right diagonal # textsize freqtext = 16 fgtext = 18 else: ymax2 = ymax ymax15 = ymax w, h = (12, 8) fig, ax = plt.subplots(1, 1, figsize=(w, h)) aspect_ratio = w / h rotdir = 1 #ax.set_aspect('equal', adjustable='box') freqtext = 20 fgtext = 20 # Spectrum parameters field = 1 if pol else 0 nu = np.logspace(np.log10(0.1), np.log10(5000), 1000) npix = hp.nside2npix(nside) # Read masks m = np.ones((len(masks), npix)) for i, mask in enumerate(masks): # Read and ud_grade mask if mask: m_temp = hp.read_map(mask, field=0, dtype=None, verbose=False) if hp.npix2nside(len(m_temp)) != nside: m[i] = hp.ud_grade(m_temp, nside) m[i, m[i, :] > 0.5] = 1 # Set all mask values to integer m[i, m[i, :] < 0.5] = 0 # Set all mask values to integer else: m[i] = m_temp # Get indices of smallest mask idx = m[np.argmax(np.sum(m, axis=1)), :] > 0.5 skyfracs = np.sum(m, axis=1) / npix * 100 print(f"Using sky fractions {skyfracs}%") # Looping over foregrounds and calculating spectra i = 0 add_error = True for fg in foregrounds.keys(): if not fg == "Sum fg.": if fg.startswith("CO"): # get closest thing to ref freq foregrounds[fg]["params"][-2], _ = find_nearest( nu, foregrounds[fg]["params"][-2]) foregrounds[fg]["spectrum"] = getspec( nu * 1e9, fg, foregrounds[fg]["params"], foregrounds[fg]["function"], field, nside, npix, idx, m, ) """ if fg.startswith("CO"):#unit conversion fudge factor foregrounds[fg]["spectrum" ] = foregrounds[fg]["spectrum"]*75 """ if add_error and foregrounds[fg]["spectrum"].shape[ 0] > 1 and not fg.startswith("CO"): thresh = 0.1 alpha = 0.5 foregrounds[fg]["spectrum"][ 0] = foregrounds[fg]["spectrum"][0] * (1 - np.exp(-( abs(foregrounds[fg]["spectrum"][0] / thresh)**alpha))) foregrounds[fg]["spectrum"][ 1] = foregrounds[fg]["spectrum"][1] / (1 - np.exp(-( abs(foregrounds[fg]["spectrum"][1] / thresh)**alpha))) if foregrounds[fg]["sum"]: if i == 0: if foregrounds[fg]["spectrum"].shape[0] == 1: # special case where first summed is 1d foregrounds["Sum fg."]["spectrum"] = np.concatenate( (foregrounds[fg]["spectrum"], foregrounds[fg]["spectrum"])).copy() else: foregrounds["Sum fg."]["spectrum"] = foregrounds[fg][ "spectrum"].copy() else: foregrounds["Sum fg."]["spectrum"] += foregrounds[fg][ "spectrum"] i += 1 # ---- Plotting foregrounds and labels ---- j = 0 for label, fg in foregrounds.items(): # Plot all fgs except sumf if fg["gradient"]: k = 0 gradient_fill( nu, fg["spectrum"][k], fill_color=fg["color"], ax=ax, alpha=0.5, linewidth=0.0, ) else: if label == "Sum fg.": ax.loglog(nu, fg["spectrum"][0], linestyle=fg["linestyle"], linewidth=2, color=fg["color"]) if long: ax2.loglog(nu, fg["spectrum"][0], linestyle=fg["linestyle"], linewidth=2, color=fg["color"]) k = 0 try: ax.loglog(nu, fg["spectrum"][1], linestyle=fg["linestyle"], linewidth=2, color=fg["color"]) if long: ax2.loglog(nu, fg["spectrum"][1], linestyle=fg["linestyle"], linewidth=2, color=fg["color"]) k = 1 except: pass elif label.startswith("CO"): lfreq = nu[np.argmax(fg["spectrum"][0])] if fg["spectrum"].shape[0] > 1: ax.loglog([lfreq, lfreq], [max(fg["spectrum"][0]), max(fg["spectrum"][1])], linestyle=fg["linestyle"], linewidth=4, color=fg["color"], zorder=1000) k = 1 else: k = 0 ax.bar( lfreq, fg["spectrum"][0], color=black, ) else: if fg["spectrum"].shape[0] == 1: ax.loglog(nu, fg["spectrum"][0], linestyle=fg["linestyle"], linewidth=4, color=fg["color"]) if long: ax2.loglog(nu, fg["spectrum"][0], linestyle=fg["linestyle"], linewidth=4, color=fg["color"]) k = 0 else: #gradient_fill(nu, fg["spectrum"][0], fill_color=fg["color"], ax=ax, alpha=0.5, linewidth=0.0,) ax.loglog(nu, np.mean(fg["spectrum"], axis=0), linestyle=fg["linestyle"], linewidth=4, color=fg["color"]) ax.fill_between(nu, fg["spectrum"][0], fg["spectrum"][1], color=fg["color"], alpha=0.5) if long: ax2.loglog(nu, np.mean(fg["spectrum"], axis=0), linestyle=fg["linestyle"], linewidth=4, color=fg["color"]) ax2.fill_between(nu, fg["spectrum"][0], fg["spectrum"][1], color=fg["color"], alpha=0.5) k = 1 if label == "Thermal Dust" and fg["spectrum"].shape[0] > 1: if long: _, fsky_idx = find_nearest(nu, 900) else: _, fsky_idx = find_nearest(nu, 700) ax.annotate( r"$f_{sky}=$" + "{:d}%".format(int(skyfracs[1])), xy=(nu[fsky_idx], fg["spectrum"][1][fsky_idx]), ha="center", va="bottom", fontsize=fgtext, color="grey", xytext=(0, 5), textcoords="offset pixels", ) ax.annotate( r"$f_{sky}=$" + "{:d}%".format(int(skyfracs[0])), xy=(nu[fsky_idx], fg["spectrum"][0][fsky_idx]), ha="center", va="top", fontsize=fgtext, color="grey", xytext=(0, -15), textcoords="offset pixels", ) if label.startswith("CO"): ax.text(lfreq, np.max(fg["spectrum"][k]) * 0.5, label, color=fg["color"], alpha=0.7, ha='right', va='center', rotation=90, fontsize=fgtext, path_effects=[ path_effects.withSimplePatchShadow(alpha=0.8, offset=(1, -1)) ], zorder=1000) else: x0, idx1 = find_nearest(nu, fg["position"]) x1, idx2 = find_nearest(nu, fg["position"] * 1.2) y0 = fg["spectrum"][k][idx1] y1 = fg["spectrum"][k][idx2] datascaling = np.log(xmin / xmax) / np.log(ymin / ymax) rotator = (datascaling / aspect_ratio) alpha = np.arctan(np.log(y1 / y0) / np.log(x1 / x0) * rotator) rotation = np.rad2deg(alpha) #*rotator ax.annotate( label, xy=(x0, y0), xytext=(0, 7), textcoords="offset pixels", rotation=rotation, rotation_mode='anchor', fontsize=fgtext, color=fg["color"], path_effects=[ path_effects.withSimplePatchShadow(alpha=0.8, offset=(1, -1)), ], ) # horizontalalignment="center") # ---- Data band ranges ---- if long: yscaletext = 0.75 yscaletextup = 1.2 else: yscaletextup = 1.03 yscaletext = 0.90 # TODO add these as args? haslam = True chipass = True spass = True cbass = True quijote = False wmap = True planck = True dirbe = True databands = { "Haslam": { "0.408\nHaslam": { "pol": False, "show": haslam, "position": [.408, ymin * yscaletextup], "range": [.406, .410], "color": purple, } }, "S-PASS": { "2.303\nS-PASS": { "pol": True, "show": spass, "position": [2.35, ymax2 * yscaletext], "range": [2.1, 2.4], "color": green, } }, "C-BASS": { "5.0\nC-BASS": { "pol": True, "show": spass, "position": [5., ymax2 * yscaletext], "range": [4., 6.], "color": blue, } }, "CHI-PASS": { "1.394\nCHI-PASS": { "pol": False, "show": chipass, "position": [1.3945, ymin * yscaletextup], "range": [1.3945 - 0.064 / 2, 1.3945 + 0.064 / 2], "color": lightred, } }, "QUIJOTE": { "11\nQUIJOTE": { "pol": True, "show": quijote, "position": [11, ymax2 * yscaletext], "range": [10., 12.], "color": orange, }, "13": { "pol": True, "show": quijote, "position": [13, ymax2 * yscaletext], "range": [12., 14.], "color": orange, }, "17": { "pol": True, "show": quijote, "position": [17, ymax2 * yscaletext], "range": [16., 18.], "color": orange, }, "19": { "pol": True, "show": quijote, "position": [20, ymax2 * yscaletext], "range": [18., 21.], "color": orange, }, "31": { "pol": True, "show": quijote, "position": [31, ymax2 * yscaletext], "range": [26., 36.], "color": orange, }, "41": { "pol": True, "show": quijote, "position": [42, ymax2 * yscaletext], "range": [35., 47.], "color": orange, } }, "Planck": { "30": { "pol": True, "show": planck, "position": [27, ymax2 * yscaletext], "range": [23.9, 34.5], "color": orange, }, # Planck 30 "44": { "pol": True, "show": planck, "position": [40, ymax2 * yscaletext], "range": [39, 50], "color": orange, }, # Planck 44 "70": { "pol": True, "show": planck, "position": [60, ymax2 * yscaletext], "range": [60, 78], "color": orange, }, # Planck 70 "100\nPlanck": { "pol": True, "show": planck, "position": [90, ymax2 * yscaletext], "range": [82, 120], "color": orange, }, # Planck 100 "143": { "pol": True, "show": planck, "position": [130, ymax2 * yscaletext], "range": [125, 170], "color": orange, }, # Planck 143 "217": { "pol": True, "show": planck, "position": [195, ymax2 * yscaletext], "range": [180, 265], "color": orange, }, # Planck 217 "353": { "pol": True, "show": planck, "position": [320, ymax2 * yscaletext], "range": [300, 430], "color": orange, }, # Planck 353 "545": { "pol": False, "show": planck, "position": [490, ymax2 * yscaletext], "range": [450, 650], "color": orange, }, # Planck 545 "857": { "pol": False, "show": planck, "position": [730, ymax2 * yscaletext], "range": [700, 1020], "color": orange, } }, # Planck 857 "DIRBE": { "DIRBE\n1250": { "pol": False, "show": dirbe, "position": [1000, ymin * yscaletextup], "range": [1000, 1540], "color": red, }, # DIRBE 1250 "2140": { "pol": False, "show": dirbe, "position": [1750, ymin * yscaletextup], "range": [1780, 2500], "color": red, }, # DIRBE 2140 "3000": { "pol": False, "show": dirbe, "position": [2500, ymin * yscaletextup], "range": [2600, 3500], "color": red, } }, # DIRBE 3000 "WMAP": { "K": { "pol": True, "show": wmap, "position": [21.8, ymin * yscaletextup], "range": [21, 25.5], "color": teal, }, "WMAP\nKa": { "pol": True, "show": wmap, "position": [31.5, ymin * yscaletextup], "range": [30, 37], "color": teal, }, "Q": { "pol": True, "show": wmap, "position": [39., ymin * yscaletextup], "range": [38, 45], "color": teal, }, "V": { "pol": True, "show": wmap, "position": [58., ymin * yscaletextup], "range": [54, 68], "color": teal, }, "W": { "pol": True, "show": wmap, "position": [90., ymin * yscaletextup], "range": [84, 106], "color": teal, } }, } # Set databands from dictonary for experiment, bands in databands.items(): for label, band in bands.items(): if band["show"]: if pol and not band["pol"]: continue # Skip non-polarization bands if band["position"][0] >= xmax or band["position"][0] <= xmin: continue # Skip databands outside range va = "bottom" if experiment in [ "WMAP", "CHI-PASS", "DIRBE", "Haslam" ] else "top" # VA for WMAP on bottom ha = "left" if experiment in [ "Planck", "WMAP", "DIRBE", ] else "center" ax.axvspan(*band["range"], color=band["color"], alpha=0.3, zorder=0, label=experiment) if long: ax2.axvspan(*band["range"], color=band["color"], alpha=0.3, zorder=0, label=experiment) if experiment in ["WMAP", "CHI-PASS", "DIRBE", "Haslam"]: ax.text(*band["position"], label, color=band["color"], va=va, ha=ha, size=freqtext, path_effects=[ path_effects.withSimplePatchShadow( alpha=0.8, offset=(1, -1)) ]) else: ax2.text(*band["position"], label, color=band["color"], va=va, ha=ha, size=freqtext, path_effects=[ path_effects.withSimplePatchShadow( alpha=0.8, offset=(1, -1)) ]) else: ax.text(*band["position"], label, color=band["color"], va=va, ha=ha, size=freqtext, path_effects=[ path_effects.withSimplePatchShadow(alpha=0.8, offset=(1, -1)) ]) # ---- Axis stuff ---- lsize = 20 # Dumb tick fix ticks = [] ticks_ = [1, 3, 10, 30, 100, 300, 1000, 3000] for i, tick in enumerate(ticks_): if tick >= xmin and tick <= xmax: ticks.append(tick) ax.set(xscale='log', yscale='log', ylim=(ymin, ymax), xlim=(xmin, xmax), xticks=ticks, xticklabels=ticks) ax.xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True)) ax.tick_params(axis='both', which='major', labelsize=lsize, direction='in') ax.tick_params(which="both", direction="in") if long: ax2.set(xscale='log', yscale='log', ylim=(ymax15, ymax2), xlim=(xmin, xmax), yticks=[ 1e4, 1e6, ], xticks=ticks, xticklabels=ticks) ax2.tick_params(axis='both', which='major', labelsize=lsize, direction='in') ax2.tick_params(which="both", direction="in") # Axis labels plt.ylabel(r"RMS brightness temperature [$\mu$K]", fontsize=lsize) plt.xlabel(r"Frequency [GHz]", fontsize=lsize) #ax.legend(loc=6,prop={'size': 20}, frameon=False) # ---- Plotting ---- plt.tight_layout(h_pad=0.3) filename = "spectrum" filename += "_pol" if pol else "" filename += "_long" if long else "" filename += "_darkmode" if darkmode else "" filename += ".png" if png else ".pdf" print("Plotting {}".format(filename)) plt.savefig(filename, bbox_inches='tight', pad_inches=0.02, transparent=True)
def make_plot(channel, time, drawLabels=True): # get the log file directory = "logs/" + channel + "/" + time filename = "rate.csv" file_path = os.path.relpath(directory + "/" + filename) with open(file_path, "r") as rate: rates = map(lambda x: x.strip(), list(rate)) start_hour = int(rates[0].split("=")[1].split("_")[0]) start_min = int(rates[0].split("=")[1].split("_")[1]) # Load data rates = rates[1:] events = [] to_delete = [] for rate in rates: if len(rate.split("*")) >= 3: events.append((int(rate.split("*")[1]), rate.split(",", 1)[1])) to_delete.append(rate) rates = [x for x in rates if x not in to_delete] old_len = len(rates) rates = remove_trailing_zeroes(rates) num_removed = old_len - len(rates) mins = map(lambda x: int(filter(lambda x: x in string.printable, x).split(",")[0]), rates) ##### XXX l = len(mins) mins = [] for i in range(l): mins.append(i) ##### XXX y_data = map(lambda x: float(x.split(",")[1]), rates) show_viewers = False try: y_data2 = map(lambda x: int(x.split(",")[2]), rates) show_viewers = True except IndexError: print rates pass dur = mins[-1] + 1 # in minutes # interval = 15 interval = get_xinterval(dur) padding_mins = start_min % interval carry = start_min / interval x_data = range(carry * interval, start_min + dur + min(num_removed, padding_mins)) x = np.array(x_data) y = np.random.randint(1, size=padding_mins) # pad it with all 0's y = np.append(y, np.array(y_data)) y = np.append(y, np.random.randint(1, size=min(num_removed, padding_mins))) # potentially add zeroes to the end if show_viewers: y2 = np.random.randint(1, size=padding_mins) # pad it with all 0's y2 = np.append(y2, np.array(y_data2)) y2 = np.append( y2, np.random.randint(1, size=min(num_removed, padding_mins)) ) # potentially add zeroes to the end # print len(x) # print len(y) # print len(y2) times = time.split("-") # 2014-08-23-04AM try: year = int(times[0]) mo = int(times[1]) day = int(times[2]) hour = start_hour minute = start_min minute = 0 # ????????????????????????????????????????????????????????????? start_time = datetime.datetime(year, mo, day, hour, minute, 0) except ValueError: # debugging. print "THIS SHOULD NEVER HAPPEN! Email me [email protected] right away!" start_time = datetime.datetime(2014, 8, 11, start_hour, start_min) # Removes leading zeroes from all the "words" in s. # "00138 hello 01AM" -> "138 hello 1AM" def removeLeadingZeroes(s): return " ".join(map(lambda x: x.lstrip("0"), s.split(" "))) def formatTime(x, pos): # timestamp = (start_time - datetime.datetime(1970, 1, 1)).total_seconds() + x*60 # now_time = datetime.datetime.fromtimestamp(timestamp) #does not convert time zones. Need time zones. now_time = datetime.timedelta(hours=float(x) / 60) + start_time if dur > 2160: # Aug 5, 8AM return removeLeadingZeroes(now_time.strftime("%b %d, %I %p")) elif interval >= 60: # 8AM return removeLeadingZeroes(now_time.strftime("%I %p")) else: # 7:45 AM return removeLeadingZeroes(now_time.strftime("%I:%M %p")) print "Drawing rate over time graph..." # START GRAPHING # plt.figure(num=None, figsize=(36, 16), dpi=80) plt.figure(num=None, figsize=(27, 12), dpi=80) # fig, ax = plt.subplots() ax = plt.axes() ax.xaxis.grid(True) ax.xaxis.set_major_formatter(FuncFormatter(formatTime)) ax.yaxis.grid(True) ax.grid(True) r = 45 if dur >= 2160: r = 270 plt.xticks(np.arange(min(x), max(x) + 1, interval), rotation=r) months = [ "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ] try: i = int(times[1]) mon = months[i] ye = int(times[2]) da = int(times[0]) plt.title("%s - %s %d, %d\n" % (channel, mon, ye, da)) except (ValueError, IndexError): plt.title(channel + "\n") settingsDict = getSettings() local_timezone = None try: local_timezone = settingsDict["timezone"] except KeyError as e: print "Setting missing:", e raise except ValueError as e: print "Malformed setting:", e raise if local_timezone.lower().strip() == "none" or local_timezone.lower().strip() == "auto": local_timezone = datetime.datetime.now(tzlocal()).tzname() # Eastern Daylight Time else: local_timezone = local_timezone.strip() split = local_timezone.split(" ") if len(split) > 1: local_timezone = "".join([word[0] for word in split]) avg_mpm = np.mean(y) plt.xlabel("\nTimes in " + local_timezone) plt.ylabel("\nMessages per minute (Avg=%0.2f)\n" % avg_mpm, color="blue") for tl in ax.get_yticklabels(): tl.set_color("blue") plt.plot(x, y, linewidth=2, color="#4422AA") if show_viewers: ax2color = "green" ax2 = ax.twinx() ax2.plot(x, y2, linewidth=4, color=ax2color) ax2.fill_between(x, 0, y2, color=ax2color, alpha=0.1) ax2.set_frame_on(True) ax2.patch.set_visible(False) ax2.yaxis.set_ticks_position("right") ax2.yaxis.set_label_position("right") avg_viewercount = np.mean(y2) ax2.set_ylabel("Viewercount (Avg=%0.1f)\n\n" % avg_viewercount, color=ax2color, labelpad=50, rotation=270) m = 1.16 * max(y) m2 = 1.16 * max(y2) ax.set_yticks(np.arange(0, m, get_yinterval(max(y)))) ax2.set_yticks(np.arange(0, m2, get_yinterval(max(y2)))) ax.set_ylim(0, m) ax2.set_ylim(0, m2) for tl in ax2.get_yticklabels(): tl.set_color(ax2color) ax.fill_between(x, 0, y, color="#5577DD") font = {"size": 25} rc("font", **font) ticklist = ax2.get_yticks() height_diff = ticklist[1] - ticklist[0] height_offset = ticklist[1] init_offset = height_offset ha = "center" for event in events: if drawLabels: plt.axvline(x=event[0] + padding_mins + carry * interval, color="red", linewidth=2, label=event[1]) s = event[1].replace("\\n", "\n") down = ax2.yaxis.get_view_interval()[1] - height_offset plt.text( event[0] + padding_mins + carry * interval, down, s, color="red", verticalalignment="top", horizontalalignment=ha, fontsize=25, rotation=0, # rotation=270, path_effects=[PathEffects.withSimplePatchShadow(linewidth=2)], ) # path_effects=[PathEffects.withStroke(linewidth=1,foreground="black")]) height_offset = (height_offset + height_diff) if height_offset == init_offset else init_offset # height_offset = height_diff - height_offset # S E L L O U T plt.text( 0.01, 0.99, "github.com/popcorncolonel/chat_stats", color="#666666", verticalalignment="top", horizontalalignment="left", fontsize=25, rotation=0, transform=ax.transAxes, ) plt.text( 0.99, 0.99, "http://twitch.tv/" + channel, color="#666666", verticalalignment="top", horizontalalignment="right", fontsize=25, rotation=0, transform=ax.transAxes, ) # plt.text(-0.05, -0.170, 'http://github.com/popcorncolonel/chat_stats', color='grey', verticalalignment='top', # horizontalalignment='left', fontsize=25, rotation=0, transform=ax.transAxes) # plt.text(1.05, -0.170, 'http://www.twitch.tv/'+channel, color='grey', verticalalignment='top', # horizontalalignment='right', fontsize=25, rotation=0, transform=ax.transAxes) # plt.show() #for running locally rather than saving the figure directory = "images/" + channel + "/" + time if not os.path.exists(directory): os.makedirs(directory) plt.savefig(directory + "/rate.png", bbox_inches="tight") print "Rate graph completed!"
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 28 19:54:58 2019 @author: xsxsz """ import numpy as np import matplotlib.pyplot as plt import matplotlib.patheffects as patheffects data=np.random.randn(10) fontsize=18 plt.plot(data) title_obj=plt.title('title') x_obj=plt.xlabel('X',alpha=0.8) y_obj=plt.ylabel('Y',alpha=0.8) title_obj.set_path_effects([patheffects.withSimplePatchShadow()]) offset_xy=(1,-1) rgbRed=(1.0,0.0,0.0) pe=patheffects.withSimplePatchShadow(offset=offset_xy,shadow_rgbFace=rgbRed) x_obj.set_path_effects([pe]) y_obj.set_path_effects([pe])
def draw_network2(graph, layout_info, ax, as_directed=None, hacknoedge=False, hacknode=False, verbose=None, **kwargs): """ fancy way to draw networkx graphs without directly using networkx # python -m ibeis.annotmatch_funcs review_tagged_joins --dpath ~/latex/crall-candidacy-2015/ --save figures4/mergecase.png --figsize=15,15 --clipwhite --diskshow # python -m dtool --tf DependencyCache.make_graph --show """ import plottool as pt patch_dict = { 'patch_frame_dict': {}, 'node_patch_dict': {}, 'edge_patch_dict': {}, 'arrow_patch_list': {}, } text_pseudo_objects = [] font_prop = pt.parse_fontkw(**kwargs) #print('font_prop = %r' % (font_prop,)) #print('font_prop.get_name() = %r' % (font_prop.get_name() ,)) # print('layout_info = %r' % (layout_info,)) node_pos = layout_info['node']['pos'] node_size = layout_info['node']['size'] splines = layout_info['graph']['splines'] # edge_startpoints = layout_info['edge']['start_pt'] if as_directed is None: as_directed = graph.is_directed() # Draw nodes for node, nattrs in graph.nodes(data=True): # shape = nattrs.get('shape', 'circle') if nattrs is None: nattrs = {} label = nattrs.get('label', None) alpha = nattrs.get('alpha', 1.0) node_color = nattrs.get('color', pt.NEUTRAL_BLUE) if node_color is None: node_color = pt.NEUTRAL_BLUE xy = node_pos[node] using_image = kwargs.get('use_image', True) and 'image' in nattrs if using_image: if hacknode: alpha_ = 0.7 else: alpha_ = 0.0 else: alpha_ = alpha node_color = fix_hex_color(node_color) #intcolor = int(node_color.replace('#', '0x'), 16) node_color = node_color[0:3] patch_kw = dict(alpha=alpha_, color=node_color) node_shape = nattrs.get('shape', 'ellipse') if node_shape == 'circle': # divide by 2 seems to work for agraph radius = min(_get_node_size(graph, node, node_size)) / 2.0 patch = mpl.patches.Circle(xy, radius=radius, **patch_kw) elif node_shape == 'ellipse': # divide by 2 seems to work for agraph width, height = np.array(_get_node_size(graph, node, node_size)) patch = mpl.patches.Ellipse(xy, width, height, **patch_kw) elif node_shape in ['none', 'box', 'rect', 'rectangle', 'rhombus']: width, height = _get_node_size(graph, node, node_size) angle = 45 if node_shape == 'rhombus' else 0 xy_bl = (xy[0] - width // 2, xy[1] - height // 2) # rounded = angle == 0 rounded = 'rounded' in graph.node.get(node, {}).get('style', '') isdiag = 'diagonals' in graph.node.get(node, {}).get('style', '') if rounded: from matplotlib import patches rpad = 20 xy_bl = np.array(xy_bl) + rpad width -= rpad height -= rpad boxstyle = patches.BoxStyle.Round(pad=rpad) patch = mpl.patches.FancyBboxPatch( xy_bl, width, height, boxstyle=boxstyle, **patch_kw) else: bbox = list(xy_bl) + [width, height] if isdiag: center_xy = vt.bbox_center(bbox) _xy = np.array(center_xy) newverts_ = [ _xy + [ 0, -height / 2], _xy + [-width / 2, 0], _xy + [ 0, height / 2], _xy + [ width / 2, 0], ] patch = mpl.patches.Polygon(newverts_, **patch_kw) else: patch = mpl.patches.Rectangle( xy_bl, width, height, angle=angle, **patch_kw) patch.center = xy #if style == 'rounded' #elif node_shape in ['roundbox']: elif node_shape == 'stack': width, height = _get_node_size(graph, node, node_size) xy_bl = (xy[0] - width // 2, xy[1] - height // 2) patch = pt.cartoon_stacked_rects(xy_bl, width, height, **patch_kw) patch.xy = xy else: raise NotImplementedError('Unknown node_shape=%r' % (node_shape,)) if True: # Add a frame around the node framewidth = nattrs.get('framewidth', 0) if framewidth > 0: framecolor = nattrs.get('framecolor', node_color) framecolor = fix_hex_color(framecolor) #print('framecolor = %r' % (framecolor,)) alpha = 1.0 if framecolor is None: framecolor = pt.BLACK alpha = 0.0 if framewidth is True: figsize = ut.get_argval('--figsize', type_=list, default=None) if figsize is not None: # HACK graphsize = max(figsize) framewidth = graphsize / 4 else: framewidth = 3.0 lw = framewidth frame = pt.make_bbox(bbox, bbox_color=framecolor, ax=ax, lw=lw, alpha=alpha) patch_dict['patch_frame_dict'][node] = frame #patch_dict[node] = patch x, y = xy text = str(node) if label is not None: #text += ': ' + str(label) text = label if kwargs.get('node_labels', hacknode or not using_image): text_args = ((x, y, text), dict(ax=ax, ha='center', va='center', fontproperties=font_prop)) text_pseudo_objects.append(text_args) patch_dict['node_patch_dict'][node] = (patch) def get_default_edge_data(graph, edge): data = graph.get_edge_data(*edge) if data is None: if len(edge) == 3 and edge[2] is not None: data = graph.get_edge_data(edge[0], edge[1], int(edge[2])) else: data = graph.get_edge_data(edge[0], edge[1]) if data is None: data = {} return data ### # Draw Edges # NEW WAY OF DRAWING EDGEES edge_pos = layout_info['edge'].get('ctrl_pts', None) if edge_pos is not None: for edge, pts in edge_pos.items(): data = get_default_edge_data(graph, edge) if data.get('style', None) == 'invis': continue alpha = data.get('alpha', None) defaultcolor = pt.BLACK[0:3] if alpha is None: if data.get('implicit', False): alpha = .5 defaultcolor = pt.GREEN[0:3] else: alpha = 1.0 color = data.get('color', defaultcolor) if color is None: color = defaultcolor color = fix_hex_color(color) color = color[0:3] #layout_info['edge']['ctrl_pts'][edge] #layout_info['edge']['start_pt'][edge] offset = 0 if graph.is_directed() else 0 #color = data.get('color', color)[0:3] start_point = pts[offset] other_points = pts[offset + 1:].tolist() # [0:3] verts = [start_point] + other_points MOVETO = mpl.path.Path.MOVETO LINETO = mpl.path.Path.LINETO if splines in ['line', 'polyline', 'ortho']: CODE = LINETO elif splines == 'curved': #CODE = mpl.path.Path.CURVE3 # CODE = mpl.path.Path.CURVE3 CODE = mpl.path.Path.CURVE4 elif splines == 'spline': CODE = mpl.path.Path.CURVE4 else: raise AssertionError('splines = %r' % (splines,)) astart_code = MOVETO astart_code = MOVETO verts = [start_point] + other_points codes = [astart_code] + [CODE] * len(other_points) end_pt = layout_info['edge']['end_pt'][edge] # HACK THE ENDPOINTS TO TOUCH THE BOUNDING BOXES if end_pt is not None: verts += [end_pt] codes += [LINETO] path = mpl.path.Path(verts, codes) figsize = ut.get_argval('--figsize', type_=list, default=None) if figsize is not None: # HACK graphsize = max(figsize) lw = graphsize / 8 width = graphsize / 15 width = ut.get_argval('--arrow-width', default=width) lw = ut.get_argval('--line-width', default=lw) #print('width = %r' % (width,)) else: width = .5 lw = 1.0 try: # Compute arrow width using estimated graph size if node_size is not None and node_pos is not None: xys = np.array(ut.take(node_pos, node_pos.keys())).T whs = np.array(ut.take(node_size, node_pos.keys())).T bboxes = vt.bbox_from_xywh(xys, whs, [.5, .5]) extents = vt.extent_from_bbox(bboxes) tl_pts = np.array([extents[0], extents[2]]).T br_pts = np.array([extents[1], extents[3]]).T pts = np.vstack([tl_pts, br_pts]) extent = vt.get_pointset_extents(pts) graph_w, graph_h = vt.bbox_from_extent(extent)[2:4] graph_dim = np.sqrt(graph_w ** 2 + graph_h ** 2) width = graph_dim * .0005 except Exception: pass if not as_directed and end_pt is not None: pass lw = data.get('lw', lw) linestyle = 'solid' linestyle = data.get('linestyle', linestyle) hatch = data.get('hatch', '') #effects = data.get('stroke', None) from matplotlib import patheffects path_effects = [] #effects_css = data.get('path_effects', None) #if effects_css is not None: # print('effects_css = %r' % (effects_css,)) # # Read data similar to Qt Style Sheets / CSS # from tinycss.css21 import CSS21Parser # css = effects_css # #css = 'stroke{ linewith: 3; foreground: r; } shadow{}' # stylesheet = CSS21Parser().parse_stylesheet(css) # if stylesheet.errors: # print('[pt.nx] css errors') # print(stylesheet.errors) # path_effects = [] # for rule in stylesheet.rules: # if rule.selector.as_css() == 'stroke': # selector = patheffects.withStroke # elif rule.selector.as_css() == 'shadow': # selector = patheffects.withSimplePatchShadow # effectkw = {} # for decl in rule.declarations: # if len(decl.value) != 1: # raise AssertionError( # 'I dont know css %r' % (decl,)) # strval = decl.value[0].as_css() # key = decl.name # val = ut.smart_cast2(strval) # effectkw[key] = val # effect = selector(**effectkw) # path_effects += [effect] ## http://matplotlib.org/1.2.1/examples/api/clippath_demo.html if data.get('shadow', None): # offset=(2, -2, shadow_rgbFace='g')) shadowkw = data.get('shadow', None) path_effects += [patheffects.withSimplePatchShadow(**shadowkw)] stroke_info = data.get('stroke', None) if stroke_info not in [None, False]: if stroke_info is True: strokekw = {} elif isinstance(stroke_info, dict): strokekw = stroke_info.copy() else: #linewidth=3, foreground='r' assert False if strokekw is not None: # Hack to increase lw strokekw['linewidth'] = lw + strokekw.get('linewidth', 3) path_effects += [patheffects.withStroke(**strokekw)] #for vert, code in path.iter_segments(): # print('code = %r' % (code,)) # print('vert = %r' % (vert,)) # if code == MOVETO: # pass #for verts, code in path.cleaned().iter_segments(): # print('code = %r' % (code,)) # print('verts = %r' % (verts,)) # pass patch = mpl.patches.PathPatch(path, facecolor='none', lw=lw, path_effects=path_effects, edgecolor=color, #facecolor=color, linestyle=linestyle, alpha=alpha, joinstyle='bevel', hatch=hatch) if as_directed: if end_pt is not None: dxy = (np.array(end_pt) - other_points[-1]) dxy = (dxy / np.sqrt(np.sum(dxy ** 2))) * .1 dx, dy = dxy rx, ry = end_pt[0], end_pt[1] patch1 = mpl.patches.FancyArrow(rx, ry, dx, dy, width=width, length_includes_head=True, color=color, head_starts_at_zero=False) else: dxy = (np.array(other_points[-1]) - other_points[-2]) dxy = (dxy / np.sqrt(np.sum(dxy ** 2))) * .1 dx, dy = dxy rx, ry = other_points[-1][0], other_points[-1][1] patch1 = mpl.patches.FancyArrow(rx, ry, dx, dy, width=width, length_includes_head=True, color=color, head_starts_at_zero=True) #ax.add_patch(patch1) patch_dict['arrow_patch_list'][edge] = (patch1) taillabel = layout_info['edge']['taillabel'][edge] #ha = 'left' #ha = 'right' ha = 'center' va = 'center' labelcolor = color # TODO allow for different colors labelcolor = data.get('labelcolor', color) labelcolor = fix_hex_color(labelcolor) labelcolor = labelcolor[0:3] if taillabel: taillabel_pos = layout_info['edge']['tail_lp'][edge] ax.annotate(taillabel, xy=taillabel_pos, xycoords='data', color=labelcolor, va=va, ha=ha, fontproperties=font_prop) headlabel = layout_info['edge']['headlabel'][edge] if headlabel: headlabel_pos = layout_info['edge']['head_lp'][edge] ax.annotate(headlabel, xy=headlabel_pos, xycoords='data', color=labelcolor, va=va, ha=ha, fontproperties=font_prop) label = layout_info['edge']['label'][edge] if label: label_pos = layout_info['edge']['lp'][edge] ax.annotate(label, xy=label_pos, xycoords='data', color=labelcolor, va=va, ha=ha, fontproperties=font_prop) patch_dict['edge_patch_dict'][edge] = patch #ax.add_patch(patch) if verbose: print('Adding %r node patches ' % (len(patch_dict['node_patch_dict'],))) print('Adding %r edge patches ' % (len(patch_dict['edge_patch_dict'],))) for frame in patch_dict['patch_frame_dict'].values(): ax.add_patch(frame) for patch1 in patch_dict['arrow_patch_list'].values(): ax.add_patch(patch1) use_collections = False if use_collections: edge_coll = mpl.collections.PatchCollection(patch_dict['edge_patch_dict'].values()) node_coll = mpl.collections.PatchCollection(patch_dict['node_patch_dict'].values()) #coll.set_facecolor(fcolor) #coll.set_alpha(alpha) #coll.set_linewidth(lw) #coll.set_edgecolor(color) #coll.set_transform(ax.transData) ax.add_collection(node_coll) ax.add_collection(edge_coll) else: for patch in patch_dict['node_patch_dict'].values(): if isinstance(patch, mpl.collections.PatchCollection): ax.add_collection(patch) else: ax.add_patch(patch) if not hacknoedge: for patch in patch_dict['edge_patch_dict'].values(): ax.add_patch(patch) for text_args in text_pseudo_objects: pt.ax_absolute_text(*text_args[0], **text_args[1]) return patch_dict
txt.arrow_patch.set_path_effects([ PathEffects.Stroke(linewidth=5, foreground="w"), PathEffects.Normal()]) ax1.grid(True, linestyle="-") pe = [PathEffects.withStroke(linewidth=3, foreground="w")] for l in ax1.get_xgridlines() + ax1.get_ygridlines(): l.set_path_effects(pe) ax2 = plt.subplot(132) arr = np.arange(25).reshape((5,5)) ax2.imshow(arr) cntr = ax2.contour(arr, colors="k") plt.setp(cntr.collections, path_effects=[ PathEffects.withStroke(linewidth=3, foreground="w")]) clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True) plt.setp(clbls, path_effects=[ PathEffects.withStroke(linewidth=3, foreground="w")]) # shadow as a path effect ax3 = plt.subplot(133) p1, = ax3.plot([0, 1], [0, 1]) leg = ax3.legend([p1], ["Line 1"], fancybox=True, loc=2) leg.legendPatch.set_path_effects([PathEffects.withSimplePatchShadow()]) plt.show()
# now plot the same data with our offset transform; # use the zorder to make sure we are below the line ax.plot(x, y, lw=3, color='gray', transform=shadow_transform, zorder=0.5*line.get_zorder()) t = ax.text(0.02, 0.5, 'Hatch shadow', fontsize=75, weight=1000, va='center') t.set_path_effects([path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx', facecolor='gray'), path_effects.PathPatchEffect(edgecolor='white', linewidth=1.1, facecolor='black')]) plt.show() import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects fig=plt.figure() ax = fig.add_axes([0,0,1,1]) line = ax.plot([0,2,3]) line[0].set_path_effects([path_effects.Stroke(linewidth=3, foreground='black'), path_effects.Normal()]) text = plt.text(0.5, 0.5, 'Hello DIR effects world!', path_effects=[path_effects.withSimplePatchShadow()]) plt.plot([0, 3, 2, 5], linewidth=5, color='blue', path_effects=[path_effects.SimpleLineShadow(), path_effects.Normal()]) plt.show()
def plot3d_gen(changes, csv_data, log_data, folder, se, rot=0, flag3D=0, count=''): xdic = dict() ydic = dict() zdic = dict() for k in sorted(csv_data): t_x = csv_data[k][changes[0]] t_y = csv_data[k][changes[1]] try: xdic[t_x].append(t_x) except KeyError: xdic[t_x] = [t_x] try: ydic[t_y].append(t_y) except KeyError: ydic[t_y] = [t_y] for t, data in log_data[k].items(): try: zdic[t][(t_x, t_y)] = data except KeyError: zdic[t] = {(t_x, t_y): data} x = [xdic[i] for i in sorted(xdic)] y = [ydic[i] for i in sorted(ydic)] x = np.array(x).T y = np.array(y) z_ = dict() z = dict() for ty in zdic: z_[ty] = [] for k in sorted(zdic[ty]): z_[ty].append(zdic[ty][k][0]) z[ty] = np.array(z_[ty]) z[ty] = z[ty].reshape((x.shape[1], x.shape[0])).T for k in sorted(z): fig = plt.figure(figsize=(16, 9)) if flag3D == 1: ax = fig.add_subplot(211, projection='3d') ax.plot_surface(x, y, z[k], rstride=1, cstride=1, cmap=cm.get_cmap('bwr')) if se != 0: ax.set_zlabel("Spearman's rho") plt.gca().zaxis.set_major_formatter(FuncFormatter(lambda x, pos=0: "{0:.3f} ".format(x))) else: ax.set_zlabel('Accuracy TOP1') plt.gca().zaxis.set_major_formatter(FuncFormatter(plot_percent)) else: ax = fig.add_subplot(111) if se != 0: cax = ax.imshow(z[k], cmap=cm.jet, interpolation='None', origin='lower', extent=[x[0][0], x[0][-1], y[0][0], y[-1][0]], aspect='auto', vmin=-1, vmax=1) bar = fig.colorbar(cax, format='%.3f') bar.set_label("Spearman's rho") else: cax = ax.imshow(z[k], cmap=cm.jet, interpolation='None', origin='lower', extent=[x[0][0], x[0][-1], y[0][0], y[-1][0]], aspect='auto', vmin=0, vmax=100) bar = fig.colorbar(cax, format='%.1f%%') bar.set_label('Accuracy TOP1') a1 = len(z[k]) a2 = len(z[k][0]) for i in xrange(a1): for j in xrange(a2): ax.text(float(j+0.5)/a2, float(i+0.5)/a1, '{0:.3}'.format(z[k][i][j]), size='medium', ha='center', va='center', transform=ax.transAxes, path_effects=[patheffects.withSimplePatchShadow(shadow_rgbFace=(1, 1, 1))]) plt.title(k) plt.xlabel(names[changes[0]]) plt.ylabel(names[changes[1]]) plt.gca().yaxis.set_major_formatter(FuncFormatter(lambda x, pos=0: "{0:.1E}".format(x))) plt.gca().xaxis.set_major_formatter(FuncFormatter(lambda x, pos=0: "{0:.1E}".format(x))) add_table(csv_data, changes) if rot == 1 and flag3D == 1 and count == '': create_output_folder('{0}/{1}'.format(folder, k)) for ii in xrange(0, 360, 20): ax.view_init(elev=30., azim=ii) plt.savefig(folder+'/'+k+'/{}'.format(ii)+names[changes[0]]+'-'+names[changes[1]]+'_'+k+'.png', bbox_inches='tight', transparent=False) else: plt.savefig(folder+'/'+count+names[changes[0]]+'-'+names[changes[1]]+'_'+k, bbox_inches='tight', transparent=False) plt.close()
def create_plots(robot, obstacles, dist_est, gt_grid, use3d=False): fig = plt.figure(figsize=(4 * 2 + 0.5, 4 * 1)) # fig = plt.figure(figsize=(3*2+0.5, 3 * 1)) # temp plt.rcParams.update({ "text.usetex": True, "font.family": "sans-serif", "font.sans-serif": ["Helvetica"] }) gs = fig.add_gridspec(1, 3) ax = fig.add_subplot(gs[0, 0]) ax.set_xlim(-8, 8) ax.set_ylim(-8, 8) ax.set_aspect('equal', adjustable='box') ax.set_xticks([-4, 0, 4]) ax.set_yticks([-4, 0, 4]) ax.set_xticklabels(['', '', '']) ax.set_yticklabels(['', '', '']) from matplotlib.cm import get_cmap cmap = get_cmap('RdBu_r') for obs in obstacles: if obs[0] == 'circle': ax.add_patch( Circle(obs[1], obs[2], path_effects=[path_effects.withSimplePatchShadow() ])) #, color=cmaps[1](0.5))) elif obs[0] == 'rect': ax.add_patch( Rectangle((obs[1][0] - float(obs[2][0]) / 2, obs[1][1] - float(obs[2][1]) / 2), obs[2][0], obs[2][1], path_effects=[path_effects.withSimplePatchShadow()], color=cmap(0.8))) #, color=cmaps[0](0.5))) print((obs[1][0] - obs[2][0] / 2, obs[1][1] - obs[2][1] / 2)) # Placeholder of the robot plot trans = ax.transData.transform lw = ((trans((1, robot.link_width)) - trans( (0, 0))) * 72 / ax.figure.dpi)[1] # q = torch.FloatTensor([-np.pi/8, -np.pi/4])#-np.pi/4]) q = torch.ones( robot.dof) * np.pi / 6 * (torch.randint(0, 3, [robot.dof]) - 1) points = robot.fkine(q)[0] points = torch.cat([torch.zeros(1, 2), points], dim=0) link_plot, = ax.plot( points[:, 0], points[:, 1], color='orange', alpha=1, lw=lw, solid_capstyle='round', path_effects=[path_effects.SimpleLineShadow(), path_effects.Normal()]) joint_plot, = ax.plot(points[:-1, 0], points[:-1, 1], 'o', color='tab:red', markersize=lw) eff_plot, = ax.plot(points[-1:, 0], points[-1:, 1], 'o', color='black', markersize=lw) # ax.axis('off') # return None, None size = [400, 400] yy, xx = torch.meshgrid(torch.linspace(-np.pi, np.pi, size[0]), torch.linspace(-np.pi, np.pi, size[1])) grid_points = torch.stack([xx, yy], axis=2).reshape((-1, 2)) est_grid = dist_est(grid_points).reshape(size) gt_grid = gt_grid.reshape(size) # gt_grid = torch.from_numpy(ndimage.gaussian_filter(gt_grid, 15)) # est_grid = torch.from_numpy(ndimage.gaussian_filter(est_grid, 3)) c_axes = [] with sns.axes_style('ticks'): for i, d in enumerate([gt_grid, est_grid], 1): # for i, d in enumerate([est_grid], 1): #TEMP # for i, d in enumerate([gt_grid], 1): # for clustering c_ax = fig.add_subplot(gs[0, i], projection='3d' if use3d else None) if use3d: from matplotlib import cm # c_ax.plot_wireframe(xx.numpy(), yy.numpy(), d.numpy(), alpha=1, #vmin=-d.max(), vmax=d.max(), # rstride=10, cstride=10, linewidth=0.1, antialiased=False, edgecolor='black') # , 'RdBu_r' surf = c_ax.plot_surface( xx.numpy(), yy.numpy(), d.numpy(), alpha=1, #vmin=-d.max(), vmax=d.max(), rstride=10, cstride=10, linewidth=0.1, antialiased=True, cmap='Greys_r', edgecolor='black') # , 'RdBu_r' cmap='Greys_r', # c_ax.plot_wireframe(xx.numpy(), yy.numpy(), d.numpy(), rstride=5, cstride=5, color='black') # surf._facecolors2d=surf._facecolor3d # surf._facecolors3d = 'face' # surf.set_edgecolor('none') # c_ax.contour3D(xx, yy, d, 50, linewidths=1, alpha=1) # c_ax.plot_surface(xx[::199, ::199], yy[::199, ::199].numpy(), np.zeros_like(yy[::199, ::199].numpy()), alpha=0.3) #, vmin=-torch.abs(d).max(), vmax=torch.abs(d).max()) #cmap='RdBu_r', else: color_mesh = c_ax.pcolormesh( xx, yy, d, cmap='RdBu_r', vmin=-torch.abs(d).max(), vmax=torch.abs( d).max()) #, alpha=0.5) # binary shading='gouraud', c_ax.contour(xx, yy, d, levels=[0], linewidths=1, alpha=0.4) #-1.5, -0.75, 0, 0.3 # ============arrows and configuration point======== sparse_stride = 20 sparse_score = d[5:-5:sparse_stride, 5:-5:sparse_stride] score_grad_x = -ndimage.sobel(sparse_score.numpy(), axis=1) score_grad_y = -ndimage.sobel(sparse_score.numpy(), axis=0) if use3d: score_grad = np.stack([ score_grad_x, score_grad_y, -(score_grad_x**2 + score_grad_y**2) ], axis=2) score_grad /= np.linalg.norm(score_grad, axis=2, keepdims=True) score_grad_x, score_grad_y, score_grad_z = [ score_grad[:, :, dim] for dim in range(3) ] else: score_grad = np.stack([score_grad_x, score_grad_y], axis=2) score_grad /= np.linalg.norm(score_grad, axis=2, keepdims=True) / 10 score_grad_x, score_grad_y = score_grad[:, :, 0], score_grad[:, :, 1] if use3d: # c_ax.quiver(xx[5:-5:sparse_stride, 5:-5:sparse_stride], yy[5:-5:sparse_stride, 5:-5:sparse_stride], sparse_score+0.05, # score_grad_x, score_grad_y, score_grad_z, # color='red') #width=1e-2, headwidth=2, headlength=5 c_ax.set_aspect('auto', adjustable='box') nearest_gridpoint = np.argmin( np.square(grid_points - q).sum(axis=1)) print( xx.reshape(-1)[nearest_gridpoint], yy.reshape(-1)[nearest_gridpoint], ) q_score = d.reshape(-1, 1)[nearest_gridpoint] # c_ax.scatter([q[0].item()], [q[1].item()], q_score+0.5, marker='o', s=40, c='orange', edgecolors='black', zorder=100) circle_patch = Circle([q[0].item(), q[1].item()], np.pi / 20, ec='k', fc="orange", alpha=1) c_ax.add_patch(circle_patch) from mpl_toolkits.mplot3d import art3d art3d.pathpatch_2d_to_3d(circle_patch, z=q_score, zdir="z") c_ax.view_init(60, 225) c_ax.set_facecolor('white') c_ax.w_xaxis.set_pane_color(ax.get_facecolor()) c_ax.w_yaxis.set_pane_color(ax.get_facecolor()) c_ax.w_zaxis.set_pane_color(ax.get_facecolor()) else: c_ax.quiver(xx[5:-5:sparse_stride, 5:-5:sparse_stride], yy[5:-5:sparse_stride, 5:-5:sparse_stride], score_grad_x, score_grad_y, color='red', width=1e-2, headwidth=2, headlength=5, pivot='mid') c_ax.set_aspect('equal', adjustable='box') c_ax.scatter([q[0].item()], [q[1].item()], marker='o', s=40, c='orange', edgecolors='black') # fig.colorbar(color_mesh, ax=c_ax) # c_ax.axis('equal') c_ax.set_xlim(-np.pi, np.pi) c_ax.set_ylim(-np.pi, np.pi) c_ax.set_xticks([-np.pi, 0, np.pi]) c_ax.set_xticklabels(['$-\pi$', '$0$', '$\pi$']) c_ax.set_yticks([-np.pi, 0, np.pi]) c_ax.set_yticklabels(['$-\pi$', '$0$', '$\pi$']) c_axes.append(c_ax) c_ax.grid(False) return est_grid.reshape(-1), c_axes
def create_plots(robot, obstacles, dist_est, checker): from matplotlib.cm import get_cmap from matplotlib.patches import Rectangle, FancyBboxPatch, Circle import seaborn as sns sns.set() import matplotlib.patheffects as path_effects cmaps = [get_cmap('Reds'), get_cmap('Blues')] plt.rcParams.update({ "text.usetex": True, "font.family": "sans-serif", "font.sans-serif": ["Helvetica"]}) if robot.dof > 2: fig = plt.figure(figsize=(3, 3)) ax = fig.add_subplot(111) #, projection='3d' elif robot.dof == 2: # Show C-space at the same time num_class = getattr(checker, 'num_class', 1) fig = plt.figure(figsize=(3*(num_class + 1), 3 * num_class)) gs = fig.add_gridspec(num_class, num_class+1) ax = fig.add_subplot(gs[:, :-1]) #sum([list(range(r*(num_class+1)+1, (r+1)*(num_class+1))) for r in range(num_class)], [])) #, projection='3d' cfg_path_plots = [] size = [400, 400] yy, xx = torch.meshgrid(torch.linspace(-np.pi, np.pi, size[0]), torch.linspace(-np.pi, np.pi, size[1])) grid_points = torch.stack([xx, yy], axis=2).reshape((-1, 2)) score_spline = dist_est(grid_points).reshape(size+[num_class]) c_axes = [] with sns.axes_style('ticks'): for cat in range(num_class): c_ax = fig.add_subplot(gs[cat, -1]) # score_diffco = checker.score(grid_points).reshape(size) # score = (torch.sign(score_diffco)+1)/2*(score_spline-score_spline.min()) + (-torch.sign(score_diffco)+1)/2*(score_spline-score_spline.max()) score = score_spline[:, :, cat] color_mesh = c_ax.pcolormesh(xx, yy, score, cmap=cmaps[cat], vmin=-torch.abs(score).max(), vmax=torch.abs(score).max()) c_support_points = checker.support_points[checker.gains[:, cat] != 0] c_ax.scatter(c_support_points[:, 0], c_support_points[:, 1], marker='.', c='black', s=1.5) contour_plot = c_ax.contour(xx, yy, score, levels=[-18, -10, 0, 3.5 if cat==0 else 2.5], linewidths=1, alpha=0.4, colors='k') #-1.5, -0.75, 0, 0.3 ax.clabel(contour_plot, inline=1, fmt='%.1f', fontsize=8) # fig.colorbar(color_mesh, ax=c_ax) # sparse_score = score[5:-5:10, 5:-5:10] # score_grad_x = -ndimage.sobel(sparse_score.numpy(), axis=1) # score_grad_y = -ndimage.sobel(sparse_score.numpy(), axis=0) # score_grad = np.stack([score_grad_x, score_grad_y], axis=2) # score_grad /= np.linalg.norm(score_grad, axis=2, keepdims=True) # score_grad_x, score_grad_y = score_grad[:, :, 0], score_grad[:, :, 1] # c_ax.quiver(xx[5:-5:10, 5:-5:10], yy[5:-5:10, 5:-5:10], score_grad_x, score_grad_y, color='red', width=2e-3, headwidth=2, headlength=5) # cfg_point = Circle(collision_cfgs[0], radius=0.05, facecolor='orange', edgecolor='black', path_effects=[path_effects.withSimplePatchShadow()]) # c_ax.add_patch(cfg_point) cfg_path, = c_ax.plot([], [], '-o', c='orange', markersize=3) cfg_path_plots.append(cfg_path) c_ax.set_aspect('equal', adjustable='box') # c_ax.axis('equal') c_ax.set_xlim(-np.pi, np.pi) c_ax.set_ylim(-np.pi, np.pi) c_ax.set_xticks([-np.pi, 0, np.pi]) c_ax.set_xticklabels(['$-\pi$', '$0$', '$\pi$'], fontsize=18) c_ax.set_yticks([-np.pi, 0, np.pi]) c_ax.set_yticklabels(['$-\pi$', '$0$', '$\pi$'], fontsize=18) # c_ax.tick_params(direction='in', reset=True) # c_ax.tick_params(which='both', direction='out', length=6, width=2, colors='r', # grid_color='r', grid_alpha=0.5) # c_ax.set_ticks('') # Plot ostacles # ax.axis('tight') ax.set_xlim(-8, 8) ax.set_ylim(-8, 8) ax.set_aspect('equal', adjustable='box') ax.set_xticks([-4, 0, 4]) ax.set_yticks([-4, 0, 4]) ax.tick_params(labelsize=18) for obs in obstacles: cat = obs[3] if len(obs) >= 4 else 1 print('{}, cat {}, {}'.format(obs[0], cat, obs)) if obs[0] == 'circle': ax.add_patch(Circle(obs[1], obs[2], path_effects=[path_effects.withSimplePatchShadow()], color=cmaps[cat](0.5))) elif obs[0] == 'rect': ax.add_patch(Rectangle((obs[1][0]-float(obs[2][0])/2, obs[1][1]-float(obs[2][1])/2), obs[2][0], obs[2][1], path_effects=[path_effects.withSimplePatchShadow()], color=cmaps[cat](0.5))) # print((obs[1][0]-obs[2][0]/2, obs[1][1]-obs[2][1]/2)) # Placeholder of the robot plot trans = ax.transData.transform lw = ((trans((1, robot.link_width))-trans((0,0)))*72/ax.figure.dpi)[1] link_plot, = ax.plot([], [], color='silver', alpha=0.1, lw=lw, solid_capstyle='round', path_effects=[path_effects.SimpleLineShadow(), path_effects.Normal()]) joint_plot, = ax.plot([], [], 'o', color='tab:red', markersize=lw) eff_plot, = ax.plot([], [], 'o', color='black', markersize=lw) if robot.dof > 2: return fig, ax, link_plot, joint_plot, eff_plot elif robot.dof == 2: return fig, ax, link_plot, joint_plot, eff_plot, cfg_path_plots
from matplotlib import patheffects import numpy as np data = np.random.randn(70) print data fontsize = 18 plt.plot(data) title = "This is figure title" x_label = "This is x axis label" y_label = "This is y axis label" title_text_obj = plt.title(title, fontsize=fontsize, verticalalignment='bottom') title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()]) # offset_xy -- set the 'angle' of the shadow # shadow_rgbFace -- set the color of the shadow # patch_alpha -- setup the transparaency of the shadow offset_xy = (1, -1) rgbRed = (1.0,0.0,0.0) alpha = 0.8 # customize shadow properties pe = patheffects.withSimplePatchShadow(offset_xy = offset_xy, shadow_rgbFace = rgbRed, patch_alpha = alpha) # apply them to the xaxis and yaxis labels xlabel_obj = plt.xlabel(x_label, fontsize=fontsize, alpha=0.5)