我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用matplotlib.pyplot.fill()。
def phase_diagram_mesh(points, values, title="Phase diagram", xlabel="Pulse Duration (s)", ylabel="Pulse Amplitude (V)", shading="flat", voronoi=False, **kwargs): # fig = plt.figure() if voronoi: from scipy.spatial import Voronoi, voronoi_plot_2d points[:,0] *= 1e9 vor = Voronoi(points) cmap = mpl.cm.get_cmap('RdGy') # colorize for pr, v in zip(vor.point_region, values): region = vor.regions[pr] if not -1 in region: polygon = [vor.vertices[i] for i in region] plt.fill(*zip(*polygon), color=cmap(v)) else: mesh = scaled_Delaunay(points) xs = mesh.points[:,0] ys = mesh.points[:,1] plt.tripcolor(xs,ys,mesh.simplices.copy(),values, cmap="RdGy",shading=shading,**kwargs) plt.xlim(min(xs),max(xs)) plt.ylim(min(ys),max(ys)) plt.title(title, size=18) plt.xlabel(xlabel, size=16) plt.ylabel(ylabel, size=16) cb = plt.colorbar() cb.set_label("Probability",size=16) return mesh
def fill_plot(): """ fill plot """ # ?????? x = np.linspace(-2*np.pi, 2*np.pi, 1000, endpoint=True) y = np.sin(x) # ?? plt.plot(x, y, color="blue", alpha=1.00) # ???? # plt.fill_between(x, y1, y2, where=None, *kwargs) plt.fill_between(x, 0, y, y > 0, color="blue", alpha=.25) plt.fill_between(x, 0, y, y < 0, color="red", alpha=.25) # ???? plt.show() return # fill_plot()
def radar_plot(): """ radar plot """ # ?????? labels = np.array(["A", "B", "C", "D", "E", "F"]) data = np.array([38, 43, 90, 67, 89, 73]) theta = np.linspace(0, 2*np.pi, len(data), endpoint=False) # ????? data = np.concatenate((data, [data[0]])) theta = np.concatenate((theta, [theta[0]])) # ???? plt.subplot(111, polar=True) # ??"theta grid"/"radar grid" plt.thetagrids(theta*(180/np.pi), labels=labels) plt.rgrids(np.arange(20, 101, 20), labels=np.arange(20, 101, 20), angle=0) plt.ylim(0, 100) # ????,?????????? plt.plot(theta, data, "bo-", linewidth=2) plt.fill(theta, data, color="red", alpha=0.25) # ???? plt.show() return # radar_plot()
def verbosePlot(object, isPoints = False, isPaths = False, isPolygons = False): import numpy as np import matplotlib.pyplot as plt for child in object: data = np.array(child) if isPolygons: plt.fill(data.T[0], data.T[1], facecolor='grey', alpha=0.3, linestyle='--', linewidth=1) elif isPaths: plt.plot(data.T[0], data.T[1], linestyle='-', linewidth=3) elif isPoints: plt.plot(data.T[0], data.T[1], linestyle='', marker='x', markersize=10, mew=3)
def plot(self, ax=None, orientation='horizontal', cutoff=False, log=False, cutoff_type='std', cutoff_val=1.5, pos=100, pos_marker='line', pos_width=0.05, pos_kwargs={}, **kwargs): if ax is None: ax = plt.gca() # Draw the violin. if ('facecolor' not in kwargs) | ('fc' not in kwargs): kwargs['facecolor'] = 'y' if ('edgecolor' not in kwargs) | ('ec' not in kwargs): kwargs['edgecolor'] = 'k' if ('alpha' not in kwargs.keys()): kwargs['alpha'] = 0.5 if 'color' in kwargs: kwargs['edgecolor'] = kwargs['color'] kwargs['facecolor'] = kwargs['color'] # Kernel density estimate for data at this position. violin, e = self.im, self.e xvals = np.linspace(e[0], e[1], len(violin)) xvals = np.hstack(([xvals[0]], xvals, [xvals[-1]])) violin = np.hstack(([0], violin, [0])) if orientation == 'horizontal': ax.fill(xvals, violin, **kwargs) elif orientation == 'vertical': ax.fill_betweenx(xvals, 0, violin, **kwargs) plt.draw_if_interactive()
def hinton(W, bg='grey', facecolors=('w', 'k')): """Draw a hinton diagram of the matrix W on the current pylab axis Hinton diagrams are a way of visualizing numerical values in a matrix/vector, popular in the neural networks and machine learning literature. The area occupied by a square is proportional to a value's magnitude, and the colour indicates its sign (positive/negative). Example usage: R = np.random.normal(0, 1, (2,1000)) h, ex, ey = np.histogram2d(R[0], R[1], bins=15) hh = h - h.T hinton.hinton(hh) """ M, N = W.shape square_x = np.array([-.5, .5, .5, -.5]) square_y = np.array([-.5, -.5, .5, .5]) ioff = False if plt.isinteractive(): plt.ioff() ioff = True plt.fill([-.5, N - .5, N - .5, - .5], [-.5, -.5, M - .5, M - .5], bg) Wmax = np.abs(W).max() for m, Wrow in enumerate(W): for n, w in enumerate(Wrow): c = plt.signbit(w) and facecolors[1] or facecolors[0] plt.fill(square_x * w / Wmax + n, square_y * w / Wmax + m, c, edgecolor=c) plt.ylim(-0.5, M - 0.5) plt.xlim(-0.5, M - 0.5) if ioff is True: plt.ion() plt.draw_if_interactive()
def fill(): """ Simple demo of the fill function. """ x = np.linspace(0, 1, 500) y = np.sin(4 * np.pi * x) * np.exp(-5 * x) plt.fill(x, y) plt.grid(True) plt.show()
def get_month_graph(msg, year, month): """ Return the uses graph of given month """ # Ensure storage directory exists try: os.mkdir('plots') except FileExistsError: pass # Get current month days date = "{0}-{1}-".format(year, month) days_month = 1 + calendar.monthrange(year, month)[1] # Create month array month_counters = [0] * days_month radius = [1] * days_month for day in enumerate(month_counters): month_counters[day[0]] = get_use_in_day(date + str(day[0]).zfill(2)) # Clear plot plt.clf() # Add titles plt.title( _('usage_statistics') + " {0}/{1}".format(month, year)) plt.xlabel( _('days_of_the_month') ) plt.xlim([1, days_month]) plt.ylabel(_('use') ) # Set grid plt.grid() # Add plots plt.plot(month_counters, color='#0099ff', linewidth=2.5) plt.plot(month_counters, 'o', color='#5e97f6') plt.fill(radius, month_counters) plt.fill_between(range(days_month), month_counters, 0, color='#99d6ff') # Save it! fname = 'plots/{0}_{1}.png'.format(year, month) plt.savefig(fname) return fname # Telegram related functions
def plotMAP(x, ax=None, error=0.01, frac=[0.65,0.95, 0.975], usehpd=True, hist={'histtype':'step'}, vlines={}, fill={}, optbins={'method':'freedman'}, *args, **kwargs): """ Plot the MAP of a given sample and add statistical info If not specified, binning is assumed from the error value or using mystats.optbins if available. if mystats module is not available, hpd keyword has no effect inputs: x dataset keywords ax axe object to use during plotting error error to consider on the estimations frac fractions of sample to highlight (def 65%, 95%, 97.5%) hpd if set, uses mystats.hpd to estimate the confidence intervals hist keywords forwarded to hist command optbins keywords forwarded to mystats.optbins command vlines keywords forwarded to vlines command fill keywords forwarded to fill command """ _x = np.ravel(x) if ax is None: ax = plt.gca() if not ('bins' in hist): bins = get_optbins(x, method=optbins['method'], ret='N') n, b, p = ax.hist(_x, bins=bins, *args, **hist) else: n, b, p = ax.hist(_x, *args, **hist) c = 0.5 * (b[:-1] + b[1:]) # dc = 0.5 * (b[:-1] - b[1:]) ind = n.argmax() _ylim = ax.get_ylim() if usehpd is True: _hpd = hpd(_x, 1 - 0.01) ax.vlines(_hpd, _ylim[0], _ylim[1], **vlines) for k in frac: nx = hpd(_x, 1. - k) ax.fill_between(nx, _ylim[0], _ylim[1], alpha=0.4 / float(len(frac)), zorder=-1, **fill) else: ax.vlines(c[ind], _ylim[0], _ylim[1], **vlines) cx = c[ n.argsort() ][::-1] cn = n[ n.argsort() ][::-1].cumsum() for k in frac: sx = cx[np.where(cn <= cn[-1] * float(k))] sx = [sx.min(), sx.max()] ax.fill_between(sx, _ylim[0], _ylim[1], alpha=0.4 / float(len(frac)), zorder=-1, **fill) theme(ax=ax) ax.set_xlabel(r'Values') ax.set_ylabel(r'Counts')