def create_execution_histogram(benchmark_data, dst): start_time = benchmark_data['start_time'] time_rates = [(f['start_tstamp'], f['end_tstamp']) for f in benchmark_data['worker_stats']] total_calls = len(time_rates) max_seconds = int(max([tr[1] - start_time for tr in time_rates]) * 1.1) max_seconds = 8 * round(max_seconds / 8) runtime_bins = np.linspace(0, max_seconds, max_seconds) def compute_times_rates(time_rates): x = np.array(time_rates) tzero = start_time tr_start_time = x[:, 0] - tzero tr_end_time = x[:, 1] - tzero N = len(tr_start_time) runtime_calls_hist = np.zeros((N, len(runtime_bins))) for i in range(N): s = tr_start_time[i] e = tr_end_time[i] a, b = np.searchsorted(runtime_bins, [s, e]) if b - a > 0: runtime_calls_hist[i, a:b] = 1 return { 'start_time': tr_start_time, 'end_time': tr_end_time, 'runtime_calls_hist': runtime_calls_hist } fig = pylab.figure(figsize=(5, 5)) ax = fig.add_subplot(1, 1, 1) time_hist = compute_times_rates(time_rates) N = len(time_hist['start_time']) line_segments = LineCollection( [[[time_hist['start_time'][i], i], [time_hist['end_time'][i], i]] for i in range(N)], linestyles='solid', color='k', alpha=0.6, linewidth=0.4) ax.add_collection(line_segments) ax.plot(runtime_bins, time_hist['runtime_calls_hist'].sum(axis=0), label='Parallel Functions', zorder=-1) yplot_step = int(np.max([1, total_calls / 20])) y_ticks = np.arange(total_calls // yplot_step + 2) * yplot_step ax.set_yticks(y_ticks) ax.set_ylim(-0.02 * total_calls, total_calls * 1.02) xplot_step = max(int(max_seconds / 8), 1) x_ticks = np.arange(int(max_seconds // xplot_step) + 1) * xplot_step ax.set_xlim(0, max_seconds) ax.set_xticks(x_ticks) for x in x_ticks: ax.axvline(x, c='k', alpha=0.2, linewidth=0.8) ax.set_xlabel("Execution Time (sec)") ax.set_ylabel("Function Call") ax.grid(False) ax.legend(loc='upper right') fig.tight_layout() dst = os.path.expanduser(dst) if '~' in dst else dst fig.savefig(dst) pylab.close(fig)
from sklearn.utils import check_random_state n = 100 x = np.arange(n) rs = check_random_state(0) y = rs.randint(-50, 50, size=(n, )) + 50. * np.log(1 + np.arange(n)) ir = IsotonicRegression() y_ = ir.fit_transform(x, y) lr = LinearRegression() lr.fit(x[:, np.newaxis], y) # 线性回归的 x 需要为 2d segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)] lc = LineCollection(segments, zorder=0) lc.set_array(np.ones(len(y))) lc.set_linewidths(0.5 * np.ones(n)) fig = plt.figure() plt.plot(x, y, 'r.', markersize=12) plt.plot(x, y_, 'g.-', markersize=12) plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-') plt.gca().add_collection(lc) # loc(设置图例显示的位置) # ncol(设置列的数量,使显示扁平化,当要表示的线段特别多的时候会有用) # 按照加图的顺序把图放在一个图里面 plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right') plt.title('Isotonic regression') plt.show()
ax = plt.axes([0., 0., 1., 1.]) similarities[np.isinf(similarities)] = 0 # similarities[similarities<1]=0 print np.max(similarities) # Plot the edges start_idx, end_idx = np.where(pos) # a sequence of (*line0*, *line1*, *line2*), where:: # linen = (x0, y0), (x1, y1), ... (xm, ym) segments = [[pca_data[i, :], pca_data[j, :]] for i in range(len(pos)) for j in range(len(pos))] values = np.abs(similarities) lc = LineCollection(segments, zorder=2, cmap=plt.cm.Greys, norm=plt.Normalize(0, values.max())) lc.set_array(similarities.flatten()) lc.set_linewidths(0.5 * np.ones(len(segments))) ax.add_collection(lc) s = 100 plt.scatter(pca_data[:, 0], pca_data[:, 1], color='red', s=s, lw=0, label='True Position') # plt.scatter(pos[:, 0], pos[:, 1], color='turquoise', s=s, lw=0, label='MDS') # plt.scatter(npos[:, 0], npos[:, 1], color='darkorange', s=s, lw=0, label='NMDS') plt.legend(scatterpoints=1, loc='best', shadow=False) plt.show()
def stackplot_t(tarray, seconds=None, start_time=None, ylabels=None, yscale=1.0): """ will plot a stack of traces one above the other assuming @tarray is an nd-array like object with format tarray.shape = numSamples, numRows @seconds = with of plot in seconds for labeling purposes (optional) @start_time is start time in seconds for the plot (optional) @ylabels a list of labels for each row ("channel") in marray @yscale with increase (mutiply) the signals in each row by this amount """ data = tarray numSamples, numRows = tarray.shape # data = np.random.randn(numSamples,numRows) # test data # data.shape = numSamples, numRows if seconds: t = seconds * np.arange(numSamples, dtype=float)/numSamples #import pdb #pdb.set_trace() if start_time: t = t+start_time xlm = (start_time, start_time+seconds) else: xlm = (0,seconds) else: t = np.arange(numSamples, dtype=float) xlm = (0,numSamples) ticklocs = [] ax = subplot(111) xlim(*xlm) # xticks(np.linspace(xlm, 10)) dmin = data.min() dmax = data.max() dr = (dmax - dmin)*0.7# Crowd them a bit. y0 = dmin y1 = (numRows-1) * dr + dmax ylim(y0, y1) segs = [] for i in range(numRows): segs.append(np.hstack((t[:,np.newaxis], yscale*data[:,i,np.newaxis]))) # print("segs[-1].shape:", segs[-1].shape) ticklocs.append(i*dr) offsets = np.zeros((numRows,2), dtype=float) offsets[:,1] = ticklocs lines = LineCollection(segs, offsets=offsets, transOffset=None, ) ax.add_collection(lines) # set the yticks to use axes coords on the y axis ax.set_yticks(ticklocs) #ax.set_yticklabels(['PG3', 'PG5', 'PG7', 'PG9']) if not ylabels: ylabels = ["%d" % ii for ii in range(numRows)] ax.set_yticklabels(ylabels) xlabel('time (s)')
PD_UP = probdens[0:int(probdens.shape[0] / 2)] PD_DOWN = probdens[int(probdens.shape[0] / 2):] for k in range(N): if V[k, k] != 0: wt[i, j] += PD_UP[k] + PD_DOWN[k] fig = plt.figure() norm = plt.Normalize(0, 1) ax = fig.add_subplot(1, 1, 1) for i in range(0, bands.shape[1]): ax.plot(qx, bands[:, i], linewidth=1.25, c='w', zorder=-10) for i in range(0, bands.shape[1]): print(bands.shape[1] - i) points = np.array([qx, bands[:, i]]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap='seismic', norm=norm) lc.set_array(wt[:, i]) lc.set_linewidth(1.0) line = ax.add_collection(lc) ax.patch.set_facecolor('black') axcb = fig.colorbar(lc) ax.set_xlim(qx[0], qx[-1]) ax.set_xlabel('kx (1/A)') ax.set_ylabel('Energy (meV)') plt.savefig('weighted_bands.png') plt.show() sys.exit() #####################################
def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, colorup='k', colordown='r', ): """ Represent the time, open, close, high, low as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. ax : an Axes instance to plot to ticksize : size of open and close ticks in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open return value is a list of lines added """ # note this code assumes if any value open, close, low, high is # missing they all are missing rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1 ] # the ticks will be from ticksize to 0 in points at the origin and # we'll translate these to the i, close location openSegments = [ ((-ticksize, 0), (0, 0)) ] # the ticks will be from 0 to ticksize in points at the origin and # we'll translate these to the i, close location closeSegments = [ ((0, 0), (ticksize, 0)) ] offsetsOpen = [ (i, open) for i, open in zip(xrange(len(opens)), opens) if open != -1 ] offsetsClose = [ (i, close) for i, close in zip(xrange(len(closes)), closes) if close != -1 ] scale = ax.figure.dpi * (1.0/72.0) tickTransform = Affine2D().scale(scale, 0.0) r,g,b = colorConverter.to_rgb(colorup) colorup = r,g,b,1 r,g,b = colorConverter.to_rgb(colordown) colordown = r,g,b,1 colord = { True : colorup, False : colordown, } colors = [colord[open<close] for open, close in zip(opens, closes) if open!=-1 and close !=-1] assert(len(rangeSegments)==len(offsetsOpen)) assert(len(offsetsOpen)==len(offsetsClose)) assert(len(offsetsClose)==len(colors)) useAA = 0, # use tuple here lw = 1, # and here rangeCollection = LineCollection(rangeSegments, colors = colors, linewidths = lw, antialiaseds = useAA, ) openCollection = LineCollection(openSegments, colors = colors, antialiaseds = useAA, linewidths = lw, offsets = offsetsOpen, transOffset = ax.transData, ) openCollection.set_transform(tickTransform) closeCollection = LineCollection(closeSegments, colors = colors, antialiaseds = useAA, linewidths = lw, offsets = offsetsClose, transOffset = ax.transData, ) closeCollection.set_transform(tickTransform) minpy, maxx = (0, len(rangeSegments)) miny = min([low for low in lows if low !=-1]) maxy = max([high for high in highs if high != -1]) corners = (minpy, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(rangeCollection) ax.add_collection(openCollection) ax.add_collection(closeCollection) return rangeCollection, openCollection, closeCollection
def plot(network, margin=0.05, ax=None, geomap=True, projection=None, bus_colors='b', line_colors={ 'Line': 'g', 'Link': 'cyan' }, bus_sizes=10, line_widths={ 'Line': 2, 'Link': 2 }, flow=None, layouter=None, title="", line_cmap=None, bus_cmap=None, boundaries=None, geometry=False, branch_components=['Line', 'Link'], jitter=None, basemap=None, basemap_parameters=None, color_geomap=None): """ Plot the network buses and lines using matplotlib and cartopy/basemap. Parameters ---------- margin : float Margin at the sides as proportion of distance between max/min x,y ax : matplotlib ax, defaults to plt.gca() Axis to which to plot the network geomap: bool/str, default True Switch to use Basemap or Cartopy (depends on what is installed). If string is passed, it will be used as a resolution argument. For Basemap users 'c' (crude), 'l' (low), 'i' (intermediate), 'h' (high), 'f' (full) are valid resolutions options. For Cartopy users '10m', '50m', '110m' are valid resolutions options. projection: cartopy.crs.Projection, defaults to None Define the projection of your geomap, only valid if cartopy is installed. If None (default) is passed the projection for cartopy is set to cartopy.crs.PlateCarree bus_colors : dict/pandas.Series Colors for the buses, defaults to "b" bus_sizes : dict/pandas.Series Sizes of bus points, defaults to 10 line_colors : dict/pandas.Series Colors for the lines, defaults to "g" for Lines and "cyan" for Links. Colors for branches other than Lines can be specified using a pandas Series with a MultiIndex. line_widths : dict/pandas.Series Widths of lines, defaults to 2. Widths for branches other than Lines can be specified using a pandas Series with a MultiIndex. flow : snapshot/pandas.Series/function/string Flow to be displayed in the plot, defaults to None. If an element of network.snapshots is given, the flow at this timestamp will be displayed. If an aggregation function is given, is will be applied to the total network flow via pandas.DataFrame.agg (accepts also function names). Otherwise flows can be specified by passing a pandas Series with MultiIndex including all necessary branch components. Use the line_widths argument to additionally adjust the size of the flow arrows. layouter : networkx.drawing.layout function, default None Layouting function from `networkx <https://networkx.github.io/>`_ which overrules coordinates given in ``network.buses[['x','y']]``. See `list <https://networkx.github.io/documentation/stable/reference/drawing.html#module-networkx.drawing.layout>`_ of available options. title : string Graph title line_cmap : plt.cm.ColorMap/str|dict If line_colors are floats, this color map will assign the colors. Use a dict to specify colormaps for more than one branch type. bus_cmap : plt.cm.ColorMap/str If bus_colors are floats, this color map will assign the colors boundaries : list of four floats Boundaries of the plot in format [x1,x2,y1,y2] branch_components : list of str Branch components to be plotted, defaults to Line and Link. jitter : None|float Amount of random noise to add to bus positions to distinguish overlapping buses basemap_parameters : dict Specify a dict with additional constructor parameters for the Basemap. Will disable Cartopy. Use this feature to set a custom projection. (e.g. `{'projection': 'tmerc', 'lon_0':10.0, 'lat_0':50.0}`) color_geomap : dict or bool Specify colors to paint land and sea areas in. If True, it defaults to `{'ocean': 'lightblue', 'land': 'whitesmoke'}`. If no dictionary is provided, colors are white. Returns ------- bus_collection, branch_collection1, ... : tuple of Collections Collections for buses and branches. """ defaults_for_branches = pd.Series({ 'Link': dict(color="cyan", width=2), 'Line': dict(color="b", width=2), 'Transformer': dict(color='green', width=2) }).rename_axis('component') if not plt_present: logger.error("Matplotlib is not present, so plotting won't work.") return if basemap is not None: logger.warning("argument `basemap` is deprecated, " "use `geomap` instead.") geomap = basemap if geomap: if not (cartopy_present or basemap_present): # Not suggesting Basemap since it is being deprecated logger.warning( "Cartopy needs to be installed to use `geomap=True`.") geomap = False # Use cartopy by default, fall back on basemap use_basemap = False use_cartopy = cartopy_present if not use_cartopy: use_basemap = basemap_present # If the user specifies basemap parameters, they prefer # basemap over cartopy. # (This means that you can force the use of basemap by # setting `basemap_parameters={}`) if basemap_present: if basemap_parameters is not None: logger.warning("Basemap is being deprecated, consider " "switching to Cartopy.") use_basemap = True use_cartopy = False if use_cartopy: if projection is None: projection = get_projection_from_crs(network.srid) if ax is None: ax = plt.gca(projection=projection) else: assert isinstance(ax, cartopy.mpl.geoaxes.GeoAxesSubplot), ( 'The passed axis is not a GeoAxesSubplot. You can ' 'create one with: \nimport cartopy.crs as ccrs \n' 'fig, ax = plt.subplots(' 'subplot_kw={"projection":ccrs.PlateCarree()})') elif ax is None: ax = plt.gca() x, y = _get_coordinates(network, layouter=layouter) axis_transform = ax.transData if geomap: if use_cartopy: axis_transform = draw_map_cartopy(network, x, y, ax, boundaries, margin, geomap, color_geomap) new_coords = pd.DataFrame(ax.projection.transform_points( axis_transform, x.values, y.values), index=network.buses.index, columns=['x', 'y', 'z']) x, y = new_coords['x'], new_coords['y'] elif use_basemap: basemap_transform = draw_map_basemap(network, x, y, ax, boundaries, margin, geomap, basemap_parameters, color_geomap) # A non-standard projection might be used; the easiest way to # support this is to tranform the bus coordinates. x, y = basemap_transform(x.values, y.values) x = pd.Series(x, network.buses.index) y = pd.Series(y, network.buses.index) if jitter is not None: x = x + np.random.uniform(low=-jitter, high=jitter, size=len(x)) y = y + np.random.uniform(low=-jitter, high=jitter, size=len(y)) if isinstance(bus_sizes, pd.Series) and isinstance(bus_sizes.index, pd.MultiIndex): # We are drawing pies to show all the different shares assert len(bus_sizes.index.levels[0].difference(network.buses.index)) == 0, \ "The first MultiIndex level of bus_sizes must contain buses" assert (isinstance(bus_colors, dict) and set(bus_colors).issuperset(bus_sizes.index.levels[1])), \ "bus_colors must be a dictionary defining a color for each element " \ "in the second MultiIndex level of bus_sizes" bus_sizes = bus_sizes.sort_index(level=0, sort_remaining=False) if geomap: bus_sizes *= projected_area_factor(ax, network.srid)**2 patches = [] for b_i in bus_sizes.index.levels[0]: s = bus_sizes.loc[b_i] radius = s.sum()**0.5 if radius == 0.0: ratios = s else: ratios = s / s.sum() start = 0.25 for i, ratio in ratios.iteritems(): patches.append( Wedge((x.at[b_i], y.at[b_i]), radius, 360 * start, 360 * (start + ratio), facecolor=bus_colors[i])) start += ratio bus_collection = PatchCollection(patches, match_original=True) ax.add_collection(bus_collection) else: c = pd.Series(bus_colors, index=network.buses.index) s = pd.Series(bus_sizes, index=network.buses.index, dtype="float").fillna(10) bus_collection = ax.scatter(x, y, c=c, s=s, cmap=bus_cmap, edgecolor='face') def as_branch_series(ser): # ensure that this function always return a multiindexed series if isinstance(ser, dict) and set(ser).issubset(branch_components): return pd.concat( { c.name: pd.Series(s, index=c.df.index) for c, s in zip(network.iterate_components(ser.keys()), ser.values()) }, names=['component', 'name']) elif isinstance(ser, pd.Series) and isinstance(ser.index, pd.MultiIndex): return ser.rename_axis(index=['component', 'name']) else: ser = pd.Series(ser, network.lines.index) return pd.concat([ser], axis=0, keys=['Line'], names=['component', 'name']).fillna(0) line_colors = as_branch_series(line_colors) line_widths = as_branch_series(line_widths) if not isinstance(line_cmap, dict): line_cmap = {'Line': line_cmap} branch_collections = [] if flow is not None: flow = (_flow_ds_from_arg( flow, network, branch_components).pipe(as_branch_series).div( sum( len(t.df) for t in network.iterate_components(branch_components)) + 100)) flow = flow.mul(line_widths[flow.index], fill_value=1) # update the line width, allows to set line widths separately from flows line_widths.update((5 * flow.abs()).pipe(np.sqrt)) arrows = directed_flow(network, flow, x=x, y=y, ax=ax, geomap=geomap, branch_colors=line_colors, branch_comps=branch_components, cmap=line_cmap['Line']) branch_collections.append(arrows) for c in network.iterate_components(branch_components): l_defaults = defaults_for_branches[c.name] l_widths = line_widths.get(c.name, l_defaults['width']) l_nums = None l_colors = line_colors.get(c.name, l_defaults['color']) if isinstance(l_colors, pd.Series): if issubclass(l_colors.dtype.type, np.number): l_nums = l_colors l_colors = None else: l_colors.fillna(l_defaults['color'], inplace=True) if not geometry: segments = (np.asarray( ((c.df.bus0.map(x), c.df.bus0.map(y)), (c.df.bus1.map(x), c.df.bus1.map(y)))).transpose(2, 0, 1)) else: from shapely.wkt import loads from shapely.geometry import LineString linestrings = c.df.geometry[lambda ds: ds != ''].map(loads) assert all(isinstance(ls, LineString) for ls in linestrings), ( "The WKT-encoded geometry in the 'geometry' column must be " "composed of LineStrings") segments = np.asarray(list(linestrings.map(np.asarray))) l_collection = LineCollection(segments, linewidths=l_widths, antialiaseds=(1, ), colors=l_colors, transOffset=ax.transData) if l_nums is not None: l_collection.set_array(np.asarray(l_nums)) l_collection.set_cmap(line_cmap.get(c.name, None)) l_collection.autoscale() ax.add_collection(l_collection) l_collection.set_zorder(3) branch_collections.append(l_collection) bus_collection.set_zorder(4) ax.update_datalim(compute_bbox_with_margins(margin, x, y)) ax.autoscale_view() if geomap: if use_cartopy: ax.outline_patch.set_visible(False) ax.axis('off') ax.set_title(title) return (bus_collection, ) + tuple(branch_collections)
def plot_multicolored_line(*, ax=None, x, y, other_y, cmap="viridis", vmin=None, vmax=None, linewidth=2, alpha=1): r"""Plots a line colored based on the values of another array. Plots the curve ``y(x)``, colored based on the values in ``other_y``. Parameters ---------- ax : :py:class:`~matplotlib.axes.Axes`, optional Axes instance, for plotting, defaults to ``None``. If ``None``, a new :py:class:`~matplotlib.figure.Figure` will be created. y : 1d array_like The dependent variable. x : 1d array_like The independent variable. other_y: 1d array_like The values whose magnitude will be converted to colors. cmap : str, optional The used colormap (defaults to "viridis"). vmin : float, optional Lower normalization limit vmax : float, optional Upper normalization limit linewidth : float, optional (default 2) Width of the plotted line alpha : float, optional (default 1) Line transparency, between 0 and 1 Returns ------- ax, line : Axes, LineCollection Main Axes and plotted line Raises ------ AssertionError If the length of `y` and `other_y` do not match. References ---------- ``matplotlib`` `example <https://matplotlib.org/gallery/lines_bars_and_markers/multicolored_line.html>`_. Examples -------- We plot a curve and color it based on the value of its first derivative. .. plot:: :include-source: import numpy as np from matplotlib import pyplot from sliceplots import plot_multicolored_line x = np.linspace(0, 3 * np.pi, 500) y = np.sin(x) dydx = np.gradient(y) * 100 # first derivative _, ax = pyplot.subplots() plot_multicolored_line(ax=ax, x=x, y=y, other_y=dydx, label="dydx") ax.set(ylabel="y", xlabel="x") """ if not (len(y) == len(other_y)): raise AssertionError("The two 'y' arrays must have the same size!") ax = ax or _make_ax() # Create a set of line segments so that we can color them individually # This creates the points as a N x 1 x 2 array so that we can stack points # together easily to get the segments. The segments array for line collection # needs to be (numlines) x (points per line) x 2 (for x and y) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) if vmin is None: vmin = np.min(other_y) if vmax is None: vmax = np.max(other_y) # Create a continuous norm to map from data points to colors norm = Normalize(vmin, vmax) lc = LineCollection(segments, cmap=cmap, norm=norm) # Set the values used for colormapping lc.set_array(other_y) lc.set_linewidth(linewidth) lc.set_alpha(alpha) line = ax.add_collection(lc) return ax, line
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=None, arrowstyle='-|>', arrowsize=10, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, label=None, node_size=300, nodelist=None, node_shape="o", connectionstyle=None, min_source_margin=0, min_target_margin=0): """Draw the edges of the graph G. This draws only the edges of the graph G. Parameters ---------- G : graph A networkx graph pos : dictionary A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. edgelist : collection of edge tuples Draw only specified edges(default=G.edges()) width : float, or array of floats Line width of edges (default=1.0) edge_color : color or array of colors (default='k') Edge color. Can be a single color or a sequence of colors with the same length as edgelist. Color can be string, or rgb (or rgba) tuple of floats from 0-1. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters. style : string Edge line style (default='solid') (solid|dashed|dotted,dashdot) alpha : float The edge transparency (default=None) edge_ cmap : Matplotlib colormap Colormap for mapping intensities of edges (default=None) edge_vmin,edge_vmax : floats Minimum and maximum for edge colormap scaling (default=None) ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. arrows : bool, optional (default=True) For directed graphs, if True draw arrowheads. Note: Arrows will be the same color as edges. arrowstyle : str, optional (default='-|>') For directed graphs, choose the style of the arrow heads. See :py:class: `matplotlib.patches.ArrowStyle` for more options. arrowsize : int, optional (default=10) For directed graphs, choose the size of the arrow head head's length and width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale` for more info. connectionstyle : str, optional (default=None) Pass the connectionstyle parameter to create curved arc of rounding radius rad. For example, connectionstyle='arc3,rad=0.2'. See :py:class: `matplotlib.patches.ConnectionStyle` and :py:class: `matplotlib.patches.FancyArrowPatch` for more info. label : [None| string] Label for legend min_source_margin : int, optional (default=0) The minimum margin (gap) at the begining of the edge at the source. min_target_margin : int, optional (default=0) The minimum margin (gap) at the end of the edge at the target. Returns ------- matplotlib.collection.LineCollection `LineCollection` of the edges list of matplotlib.patches.FancyArrowPatch `FancyArrowPatch` instances of the directed edges Depending whether the drawing includes arrows or not. Notes ----- For directed graphs, arrows are drawn at the head end. Arrows can be turned off with keyword arrows=False. Be sure to include `node_size` as a keyword argument; arrows are drawn considering the size of nodes. Examples -------- >>> G = nx.dodecahedral_graph() >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) >>> G = nx.DiGraph() >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)]) >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) >>> alphas = [0.3, 0.4, 0.5] >>> for i, arc in enumerate(arcs): # change alpha values of arcs ... arc.set_alpha(alphas[i]) Also see the NetworkX drawing examples at https://networkx.github.io/documentation/latest/auto_examples/index.html See Also -------- draw() draw_networkx() draw_networkx_nodes() draw_networkx_labels() draw_networkx_edge_labels() """ try: import matplotlib.pyplot as plt from matplotlib.colors import colorConverter, Colormap, Normalize from matplotlib.collections import LineCollection from matplotlib.patches import FancyArrowPatch import numpy as np except ImportError as e: raise ImportError("Matplotlib required for draw()") from e except RuntimeError: print("Matplotlib unable to open display") raise if ax is None: ax = plt.gca() if edgelist is None: edgelist = list(G.edges()) if not edgelist or len(edgelist) == 0: # no edges! if not G.is_directed() or not arrows: return LineCollection(None) else: return [] if nodelist is None: nodelist = list(G.nodes()) # FancyArrowPatch handles color=None different from LineCollection if edge_color is None: edge_color = 'k' # set edge positions edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) # Check if edge_color is an array of floats and map to edge_cmap. # This is the only case handled differently from matplotlib if np.iterable(edge_color) and (len(edge_color) == len(edge_pos)) \ and np.alltrue([isinstance(c, Number) for c in edge_color]): if edge_cmap is not None: assert (isinstance(edge_cmap, Colormap)) else: edge_cmap = plt.get_cmap() if edge_vmin is None: edge_vmin = min(edge_color) if edge_vmax is None: edge_vmax = max(edge_color) color_normal = Normalize(vmin=edge_vmin, vmax=edge_vmax) edge_color = [edge_cmap(color_normal(e)) for e in edge_color] if (not G.is_directed() or not arrows): edge_collection = LineCollection(edge_pos, colors=edge_color, linewidths=width, antialiaseds=(1, ), linestyle=style, transOffset=ax.transData, alpha=alpha) edge_collection.set_cmap(edge_cmap) edge_collection.set_clim(edge_vmin, edge_vmax) edge_collection.set_zorder(1) # edges go behind nodes edge_collection.set_label(label) ax.add_collection(edge_collection) return edge_collection arrow_collection = None if G.is_directed() and arrows: # Note: Waiting for someone to implement arrow to intersection with # marker. Meanwhile, this works well for polygons with more than 4 # sides and circle. def to_marker_edge(marker_size, marker): if marker in "s^>v<d": # `large` markers need extra space return np.sqrt(2 * marker_size) / 2 else: return np.sqrt(marker_size) / 2 # Draw arrows with `matplotlib.patches.FancyarrowPatch` arrow_collection = [] mutation_scale = arrowsize # scale factor of arrow head # FancyArrowPatch doesn't handle color strings arrow_colors = colorConverter.to_rgba_array(edge_color, alpha) for i, (src, dst) in enumerate(edge_pos): x1, y1 = src x2, y2 = dst shrink_source = 0 # space from source to tail shrink_target = 0 # space from head to target if np.iterable(node_size): # many node sizes source, target = edgelist[i][:2] source_node_size = node_size[nodelist.index(source)] target_node_size = node_size[nodelist.index(target)] shrink_source = to_marker_edge(source_node_size, node_shape) shrink_target = to_marker_edge(target_node_size, node_shape) else: shrink_source = shrink_target = to_marker_edge( node_size, node_shape) if shrink_source < min_source_margin: shrink_source = min_source_margin if shrink_target < min_target_margin: shrink_target = min_target_margin if len(arrow_colors) == len(edge_pos): arrow_color = arrow_colors[i] elif len(arrow_colors) == 1: arrow_color = arrow_colors[0] else: # Cycle through colors arrow_color = arrow_colors[i % len(arrow_colors)] if np.iterable(width): if len(width) == len(edge_pos): line_width = width[i] else: line_width = width[i % len(width)] else: line_width = width arrow = FancyArrowPatch((x1, y1), (x2, y2), arrowstyle=arrowstyle, shrinkA=shrink_source, shrinkB=shrink_target, mutation_scale=mutation_scale, color=arrow_color, linewidth=line_width, connectionstyle=connectionstyle, linestyle=style, zorder=1) # arrows go behind nodes # There seems to be a bug in matplotlib to make collections of # FancyArrowPatch instances. Until fixed, the patches are added # individually to the axes instance. arrow_collection.append(arrow) ax.add_patch(arrow) # update view minx = np.amin(np.ravel(edge_pos[:, :, 0])) maxx = np.amax(np.ravel(edge_pos[:, :, 0])) miny = np.amin(np.ravel(edge_pos[:, :, 1])) maxy = np.amax(np.ravel(edge_pos[:, :, 1])) w = maxx - minx h = maxy - miny padx, pady = 0.05 * w, 0.05 * h corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady) ax.update_datalim(corners) ax.autoscale_view() ax.tick_params(axis='both', which='both', bottom=False, left=False, labelbottom=False, labelleft=False) return arrow_collection
def main(): # Setup plot f, ax = plt.subplots(1, 1) # Plot slalom markers markers = [ # x y [60, 30], [60, 60], [60, 120], [60, 150], [60, 180], [60, 210], [60, 240], [60, 300], ] ax.scatter([p[0] for p in markers], [p[1] for p in markers], label="markers", s=20) # Input lines m = 16 # robot margin m_diag = m * math.sqrt(2) / 2 # m when at a diagonal d2 = 10 # D2 extra margin d8 = 10 # D8 extra margin d10 = 10 # D10 extra margin lines = list( map( lambda i: Line(Waypoint(i[0], i[1]), Waypoint(i[2], i[3])), [ # x1 y1 x2 y2 [60 - m - d2, 50, 0 + m, 50], [60 + m_diag, 120 - m_diag, 120 - m_diag, 60 + m_diag], [60 + m, 180, 120 - m, 180], [60, 240 + m + d8, 60, 300 - m], [60 - m - d10, 300, 0 + m, 300], [60, 300 + m, 60, 360 - m], [60 + m + d10, 300, 120 - m, 300], [60, 240 + m + d8, 60, 300 - m], [60 - m, 180, 0 + m, 180], [60 - m_diag, 120 - m_diag, 0 + m_diag, 60 + m_diag], [60 + m + d2, 60, 120 - m, 60], ])) # Plot input lines lines_x = [] lines_y = [] for line in lines: lines_x.append([line.p1.x, line.p2.x]) lines_y.append([line.p1.y, line.p2.y]) ax.add_collection( LineCollection([list(zip(x, y)) for x, y in zip(lines_x, lines_y)], label="input lines")) # Get optimal start_t = time.time() trajectory = find_optimal_trajectory(lines, 5, MAX_V, MAX_OMEGA, MAX_A)[0] end_t = time.time() print(f"Calculation time: {end_t - start_t} s") # Plot optimal path_x = np.array([p[0].x for p in trajectory]) path_y = np.array([p[0].y for p in trajectory]) ax.scatter(path_x, path_y, label="optimal", s=12) # Write optimal traj to file with open("gen.csv", "w") as file: file.write("x,y,t\n") for i in trajectory: file.write(f"{str(i[0])},{i[1]}\n") print("Trajectory written to gen.csv") # Display plot ax.legend(loc="upper left") plt.gca().set_aspect("equal", adjustable="box") plt.gca().invert_xaxis() plt.show()
def plot_lines(self, ax, lc_kwargs={}): lc = LineCollection(layer_to_lines(self.lines), **lc_kwargs) ax.add_collection(lc) ax.axis('tight') ax.axis('square')
def file_plotter(logname): """Plots a single timing log file. Arguments: logname -- the log file (str) """ summary_stats = np.zeros((NUM_STATS,workers)) offset = 0 for i in range(0,workers): (segments, colors, offset) = worker_parser(logname, offset, summary_stats) if do_plot or save_eps: cmap = ListedColormap(colors) lc = LineCollection(segments, cmap=cmap) # this (probably?) sets which of cmap's colors to use lc.set_array(np.arange(0, len(colors))) lc.set_linewidth(line_width) plt.gca().add_collection(lc) # min()/max() finds single digit (i.e., flattens and then finds) # this makes sure there aren't messed up/"reversed" timestamps if np.array(segments).min() < 0: print 'WARNING: encountered negative value in ' + logname + '!' #plt.axis('auto') # to get auto max-lims # ensure we modify global var (rather than create local one) global max_xlim max_xlim = max(max_xlim, np.array(segments).max()+0.5) ## pretty plot if do_plot or save_eps: # gca() returns actual Axes object plt.gca().set_xlim(left=0) plt.gca().minorticks_on() plt.xlabel('Time (s)', fontsize=FONTSIZE) # or plt.gca().set_xlabel(...) plt.tick_params(axis='x', which='major', labelsize=XLABELSIZE) plt.ylim(0.25, workers+0.75) plt.yticks(range(1, workers+1)) #plt.gca().set_yticklabels([r'W$_{' + str(i) + '}$' for i in range(workers,0,-1)]) plt.gca().set_yticklabels([str(i) for i in range(workers,0,-1)]) plt.gca().tick_params(axis='y',which='both',right='off',left='off') plt.ylabel('Workers', fontsize=FONTSIZE) plt.tick_params(axis='y', which='major', labelsize=YLABELSIZE) plt.title(logname, fontsize=FONTSIZE) ## print statistics for w in range(0,workers): for s in range(1, NUM_STATS): summary_stats[s, w] /= float(summary_stats[T_TOTAL, w]) stats = summary_stats[1:NUM_STATS] avg_stats = tuple([s.mean()*100 for s in stats]) min_stats = tuple([s.min()*100 for s in stats]) max_stats = tuple([s.max()*100 for s in stats]) print '====================================================================================' print ' ' + logname print '====================================================================================' print ' | compute | ss comm | comm | local barrier | ltw barrier | global barrier' print '----+-----------+---------+----------+---------------+-------------+----------------' print 'avg | %6.3f%% | %6.3f%% | %6.3f%% | %6.3f%% | %6.3f%% | %6.3f%%' % avg_stats print 'min | %6.3f%% | %6.3f%% | %6.3f%% | %6.3f%% | %6.3f%% | %6.3f%%' % min_stats print 'max | %6.3f%% | %6.3f%% | %6.3f%% | %6.3f%% | %6.3f%% | %6.3f%%' % max_stats print ''
# s:点的大小(一维数组)随d(1/标准差,意味着标准差越大,点的形状越小)变化,c:颜色(一维数组)随坐标变化 #绘制边界线(即两股票点的连接线) start_idx, end_idx = np.where( non_zero) # 只有条件non_zero,所以返回non_zero.nonzero(),即返回有两个元素的元组, # 第一个元素为非零的数在O轴即竖轴的下标,第二个元素为非零的数在1轴即横轴的下标 # a sequence of (*line0*, *line1*, *line2*), where::linen = (x0, y0), (x1, y1), ... (xm, ym) segments = [[embedding[:, start], embedding[:, stop]] for start, stop in zip(start_idx, end_idx)] #embedding为二维数组 values = np.abs(partial_correlations[non_zero]) # 用non_zero遮罩后的15个元素的数组 lc = LineCollection(segments, zorder=0, cmap=plt.cm.hot_r, norm=plt.Normalize( 0, .7 * values.max())) # zorder:调整层次,cmap:colormap lc.set_array(values) lc.set_linewidths(6 * values) ax.add_collection(lc) # Add a label to each node. The challenge here is that we want to # position the labels to avoid overlap with other labels for index, (name, label, (x, y)) in enumerate(zip(names, labels, embedding.T)): dx = x - embedding[0] dx[index] = 1 dy = y - embedding[1] dy[index] = 1 this_dx = dx[np.argmin(np.abs(dy))]
cax = divider.append_axes('right', size='5%', pad=0.025) ax.plot([0, 1], [0, 1], color='lightgray') ax.axvline(0, lw=0.5, color='lightgray') ax.axhline(1, lw=0.5, color='lightgray') fpr, tpr, t = roc_curve(df['label'], df['probabilities'], drop_intermediate=False) nth = 5000 fpr, tpr, t = fpr[::nth], tpr[::nth], t[::nth] points = np.array([fpr, tpr]).T.reshape((-1, 1, 2)) segments = np.concatenate([points[:-1], points[1:]], axis=1) col = LineCollection(segments, zorder=3) col.set_array(t) col.set_clim(0, 1) col.set_cmap('inferno') ax.add_collection(col) rocs = np.array([ roc_auc_score(fold['label'], fold['probabilities']) for _, fold in df.groupby('cv_fold') ]) ax.set_title(f'ROC-AUC: {rocs.mean():.4f} ± {rocs.std():.4f}') ax.set_ylim(0, 1.025) ax.set_xlim(-0.025, 1) ax.set_aspect(1)
# The constellation lines will each begin at the x,y of one star and end # at the x,y of another. We have to "rollaxis" the resulting coordinate # array into the shape that matplotlib expects. xy1 = stars[['x', 'y']].loc[edges_star1].values xy2 = stars[['x', 'y']].loc[edges_star2].values lines_xy = np.rollaxis(np.array([xy1, xy2]), 1) # Time to build the figure! fig, ax = plt.subplots(figsize=[9, 9]) # Draw the constellation lines. ax.add_collection(LineCollection(lines_xy, colors='#00f2')) # Draw the stars. ax.scatter(stars['x'][bright_stars], stars['y'][bright_stars], s=marker_size, color='k') # Draw the comet positions, and label them with dates. comet_color = '#f00' offset = 0.002 ax.plot(comet_x, comet_y, '+', c=comet_color, zorder=3)
def odd_import(self, ax, odd): if odd[1] == -1: odd[1] = 0 self.odd_tool.update_odd() file_name = self.odd_tool.odd_list[odd[0]] odd_path = 'scenarios/' + str(odd[0]) + '/' + file_name[odd[1]] + '.json' with open(odd_path, 'r') as load_f: load_dict = load(load_f) list_dict = list(load_dict.keys()) scenario = load_dict[list_dict[0]] try: lines1 = scenario['lines']['boundary_lines'] lines2 = scenario['lines']['solid_lines'] lines3 = scenario['lines']['dashed_lines'] lines4 = scenario['lines']['thick_lines'] objects = scenario['objects'] common_rotation = scenario['common_rotation'] common_offset = scenario['common_offset'] except Exception: lines1 = [] lines2 = [] lines3 = [] lines4 = [] objects = [] common_rotation = 0.0 common_offset = [0, 0] QMessageBox.warning(self, 'Warning', 'Scenario file format error!') boundary_lines = self.line_rotation(lines1, common_rotation) solid_lines = self.line_rotation(lines2, common_rotation) dashed_lines = self.line_rotation(lines3, common_rotation) thick_lines = self.line_rotation(lines4, common_rotation) for l in boundary_lines: for m in l: m[0] = (m[0] + common_offset[0]) * self.zoom_factor m[1] = (m[1] + common_offset[1]) * self.zoom_factor for l in solid_lines: for m in l: m[0] = (m[0] + common_offset[0]) * self.zoom_factor m[1] = (m[1] + common_offset[1]) * self.zoom_factor for l in dashed_lines: for m in l: m[0] = (m[0] + common_offset[0]) * self.zoom_factor m[1] = (m[1] + common_offset[1]) * self.zoom_factor for l in thick_lines: for m in l: m[0] = (m[0] + common_offset[0]) * self.zoom_factor m[1] = (m[1] + common_offset[1]) * self.zoom_factor line_segments1 = LineCollection(boundary_lines, linewidths=2, colors=(0, 0, 0), linestyles='solid') line_segments1.set_zorder(0) line_segments2 = LineCollection(solid_lines, linewidths=1, colors=(0.1, 0.1, 0.1), linestyles='solid') line_segments2.set_zorder(0) line_segments3 = LineCollection(dashed_lines, linewidths=1, colors=(0.2, 0.2, 0.2), linestyles=(0, (20, 20))) line_segments3.set_zorder(0) line_segments4 = LineCollection(thick_lines, linewidths=4.5, colors=(0.8, 0.8, 0.8), linestyles='solid') line_segments4.set_zorder(0) self.ax.add_collection(line_segments1) self.ax.add_collection(line_segments2) self.ax.add_collection(line_segments3) self.ax.add_collection(line_segments4) patch = [] for obj in range(len(objects)): objects_xy = self.object_rotation(objects[obj][1], common_rotation) objects_xy[0] = objects_xy[0] + common_offset[0] objects_xy[1] = objects_xy[1] + common_offset[1] objects_r = objects[obj][2] + common_rotation patch.append(self.add_object(objects[obj][0], objects_xy, objects_r)) self.ax.text((objects_xy[0]) * self.zoom_factor, (objects_xy[1] + 2.5) * self.zoom_factor, 'obj' + str(obj + 1), fontsize=10) patch_segment = PatchCollection(patch, facecolors='gray') patch_segment.set_zorder(2) ax.add_collection(patch_segment) return patch
def plot_diagram(self, pers_dgm, skew=True, ax=None, out_file=None): """ Plot a persistence diagram. Parameters ---------- pers_dgm : (-,2) numpy.ndarray A persistence diagram. skew : boolean Flag indicating if diagram needs to first be converted to birth-persistence coordinates (default: True). ax : matplotlib.Axes Instance of a matplotlib.Axes object in which to plot (default: None, generates a new figure) out_file : str Path and file name including extension to save the figure (default: None, figure not saved). Returns ------- matplotlib.Axes The matplotlib.Axes which contains the persistence diagram """ pers_dgm = np.copy(pers_dgm) if skew: pers_dgm[:, 1] = pers_dgm[:, 1] - pers_dgm[:, 0] ylabel = 'persistence' else: ylabel = 'death' # setup plot range plot_buff_frac = 0.05 bmin = np.min((np.min(pers_dgm[:, 0]), np.min(self._bpnts))) bmax = np.max((np.max(pers_dgm[:, 0]), np.max(self._bpnts))) b_plot_buff = (bmax - bmin) * plot_buff_frac bmin -= b_plot_buff bmax += b_plot_buff pmin = np.min((np.min(pers_dgm[:, 1]), np.min(self._ppnts))) pmax = np.max((np.max(pers_dgm[:, 1]), np.max(self._ppnts))) p_plot_buff = (pmax - pmin) * plot_buff_frac pmin -= p_plot_buff pmax += p_plot_buff ax = ax or plt.gca() ax.set_xlim(bmin, bmax) ax.set_ylim(pmin, pmax) # compute reasonable line width for pixel overlay (initially 1/50th of the width of a pixel) linewidth = (1/50 * self.pixel_size) * 72 * plt.gcf().bbox_inches.width * ax.get_position().width / \ np.min((bmax - bmin, pmax - pmin)) # plot the persistence image grid if skew: hlines = np.column_stack(np.broadcast_arrays(self._bpnts[0], self._ppnts, self._bpnts[-1], self._ppnts)) vlines = np.column_stack(np.broadcast_arrays(self._bpnts, self._ppnts[0], self._bpnts, self._ppnts[-1])) lines = np.concatenate([hlines, vlines]).reshape(-1, 2, 2) line_collection = LineCollection(lines, color='black', linewidths=linewidth) ax.add_collection(line_collection) # plot persistence diagram ax.scatter(pers_dgm[:, 0], pers_dgm[:, 1]) # plot diagonal if necessary if not skew: min_diag = np.min((np.min(ax.get_xlim()), np.min(ax.get_ylim()))) max_diag = np.min((np.max(ax.get_xlim()), np.max(ax.get_ylim()))) ax.plot([min_diag, max_diag], [min_diag, max_diag]) # fix and label axes ax.set_aspect('equal') ax.set_xlabel('birth') ax.set_ylabel(ylabel) # optionally save figure if out_file: plt.savefig(out_file, bbox_inches='tight') return ax
def martin_plot_frame(well_data, time, vrange=(-100, 100), autocad_path=None, strike=120., hydro_path=None, origin=np.array([2579332., 1247600., 514.]), title=None): """ Plot single frame of wells colored by strain. Take map and cross section from Vero and my presentation to MT partners :param well_data: Output from extract_wells :param time: Time plot signals for :return: """ fig = plt.figure(figsize=(15, 8)) spec = GridSpec(ncols=8, nrows=8, figure=fig) ax3d = fig.add_subplot(spec[:6, :4], projection='3d') ax_x = fig.add_subplot(spec[:7, 4:]) ax_hydro = fig.add_subplot(spec[7:, :]) if title: fig.suptitle(title, fontsize=20) # Cross section plane (strike 320) r = np.deg2rad(360 - strike) normal = np.array([-np.sin(r), -np.cos(r), 0.]) normal /= linalg.norm(normal) new_strk = np.array([np.sin(r), -np.cos(r), 0.]) new_strk /= linalg.norm(new_strk) change_b_mat = np.array([new_strk, [0, 0, 1], normal]) for afile in glob('{}/*.csv'.format(autocad_path)): df_cad = pd.read_csv(afile) lines = df_cad.loc[df_cad['Name'] == 'Line'] arcs = df_cad.loc[df_cad['Name'] == 'Arc'] for i, line in lines.iterrows(): xs = np.array([line['Start X'], line['End X']]) ys = np.array([line['Start Y'], line['End Y']]) zs = np.array([line['Start Z'], line['End Z']]) # Proj pts = np.column_stack([xs, ys, zs]) proj_pts = np.dot(pts - origin, normal)[:, None] * normal proj_pts = pts - origin - proj_pts proj_pts = np.matmul(change_b_mat, proj_pts.T) ax3d.plot(xs, ys, zs, color='lightgray', zorder=210, linewidth=0.5) ax_x.plot(proj_pts[0, :], proj_pts[1, :], color='lightgray', zorder=110, alpha=0.5, linewidth=0.5) for i, arc in arcs.iterrows(): # Stolen math from Melchior if not np.isnan(arc['Extrusion Direction X']): rotaxang = [arc['Extrusion Direction X'], arc['Extrusion Direction Y'], arc['Extrusion Direction Z'], arc['Total Angle']] rad = np.linspace(arc['Start Angle'], arc['Start Angle'] + arc['Total Angle']) dx = np.sin(np.deg2rad(rad)) * arc['Radius'] dy = np.cos(np.deg2rad(rad)) * arc['Radius'] dz = np.zeros(dx.shape[0]) phi1 = -np.arctan2( linalg.norm( np.cross(np.array([rotaxang[0], rotaxang[1], rotaxang[2]]), np.array([0, 0, 1]))), np.dot(np.array([rotaxang[0], rotaxang[1], rotaxang[2]]), np.array([0, 0, 1]))) DX = dx * np.cos(phi1) + dz * np.sin(phi1) DY = dy DZ = dz * np.cos(phi1) - dx * np.sin(phi1) # ax.plot(DX, DY, DZ, color='r') phi2 = np.arctan(rotaxang[1] / rotaxang[0]) fdx = (DX * np.cos(phi2)) - (DY * np.sin(phi2)) fdy = (DX * np.sin(phi2)) + (DY * np.cos(phi2)) fdz = DZ x = fdx + arc['Center X'] y = fdy + arc['Center Y'] z = fdz + arc['Center Z'] # projected pts pts = np.column_stack([x, y, z]) proj_pts = np.dot(pts - origin, normal)[:, None] * normal proj_pts = pts - origin - proj_pts proj_pts = np.matmul(change_b_mat, proj_pts.T) ax3d.plot(x, y, z, color='lightgray', zorder=210, linewidth=0.5) ax_x.plot(proj_pts[0, :], proj_pts[1, :], color='lightgray', zorder=110, alpha=0.5, linewidth=0.5) elif not np.isnan(arc['Start X']): v1 = -1. * np.array([arc['Center X'] - arc['Start X'], arc['Center Y'] - arc['Start Y'], arc['Center Z'] - arc['Start Z']]) v2 = -1. * np.array([arc['Center X'] - arc['End X'], arc['Center Y'] - arc['End Y'], arc['Center Z'] - arc['End Z']]) rad = np.linspace(0, np.deg2rad(arc['Total Angle']), 50) # get rotation vector (norm is rotation angle) rotvec = np.cross(v2, v1) rotvec /= linalg.norm(rotvec) rotvec = rotvec[:, np.newaxis] * rad[np.newaxis, :] Rs = R.from_rotvec(rotvec.T) pt = np.matmul(v1, Rs.as_matrix()) # Projected pts x = arc['Center X'] + pt[:, 0] y = arc['Center Y'] + pt[:, 1] z = arc['Center Z'] + pt[:, 2] pts = np.column_stack([x, y, z]) proj_pts = np.dot(pts - origin, normal)[:, None] * normal proj_pts = pts - origin - proj_pts proj_pts = np.matmul(change_b_mat, proj_pts.T) ax3d.plot(x, y, z, color='lightgray', zorder=210, linewidth=0.5) ax_x.plot(proj_pts[0, :], proj_pts[1, :], color='lightgray', zorder=210, alpha=0.5, linewidth=0.5) well_dict = create_FSB_boreholes() # cmap = ListedColormap(sns.color_palette('icefire', 21).as_hex()) cmap = ListedColormap(sns.color_palette('coolwarm', 21).as_hex()) for well, w_dict in well_data.items(): pts = [] if well == 'B4': continue for feature_dep in w_dict['depth']: feature_dep -= w_dict['depth'][0] pts.append(depth_to_xyz(well_dict, well, feature_dep)) strains = w_dict['data'][:, np.argmin(np.abs(time - w_dict['times']))] # Project well points and fault intersection points onto cross section pts = np.array(pts) proj_pts = np.dot(pts - origin, normal)[:, None] * normal proj_pts = pts - origin - proj_pts proj_pts = np.matmul(change_b_mat, proj_pts.T) proj_pts = proj_pts[:2, :] proj_pts = proj_pts.T.reshape([-1, 1, 2]) ax3d.scatter(pts[0, 0], pts[0, 1], pts[0, 2], color='darkgray', linewidth=1.5, s=15., zorder=110) pts = pts.reshape([-1, 1, 3]) try: fault_pts = [depth_to_xyz(well_dict, well, fault_depths[well][i]) for i in (0, 1)] fault_pts = np.array(fault_pts) p_fault_pts = np.dot(fault_pts - origin, normal)[:, None] * normal p_fault_pts = fault_pts - origin - p_fault_pts p_fault_pts = np.matmul(change_b_mat, p_fault_pts.T) p_fault_pts = p_fault_pts[:2, :].T # Plot fault intersection points ax_x.scatter(p_fault_pts[:, 0], p_fault_pts[:, 1], c='purple', marker='x', s=15., zorder=105) except KeyError as e: # Borehole doesn't intersect fault pass # Make segments proj_seggies = np.concatenate([proj_pts[:-1], proj_pts[1:]], axis=1) seggies = np.concatenate([pts[:-1], pts[1:]], axis=1) col_norm = plt.Normalize(vrange[0], vrange[1]) lc = Line3DCollection(seggies, cmap=cmap, norm=col_norm) lc_proj = LineCollection(proj_seggies, cmap=cmap, norm=col_norm) # Set the values used for colormapping lc.set_array(strains) lc.set_linewidth(3.) lc_proj.set_array(strains) lc_proj.set_linewidth(3.) line = ax3d.add_collection3d(lc) line_x = ax_x.add_collection(lc_proj) fig.colorbar(line_x, ax=ax3d, label=r'$\mu\epsilon$') # Formatting ax3d.set_xlim([2579310, 2579355]) ax3d.set_ylim([1247555, 1247600]) ax3d.set_zlim([485, 530]) # ax3d.view_init(elev=30., azim=-112) ax3d.view_init(elev=75, azim=-120.) ax3d.margins(0.) ax3d.set_xticks([]) ax3d.set_xticklabels([]) ax3d.set_yticks([]) ax3d.set_yticklabels([]) ax3d.set_zticks([]) ax3d.set_zticklabels([]) # Cross section ax_x.set_xlim([-30, 5]) ax_x.axis('equal') ax_x.spines['top'].set_visible(False) ax_x.spines['bottom'].set_visible(False) ax_x.spines['left'].set_visible(False) ax_x.yaxis.set_ticks_position('right') ax_x.tick_params(direction='in', bottom=False, labelbottom=False) ax_x.set_yticks([-30, -20, -10, 0]) ax_x.set_yticklabels(['30', '20', '10', '0']) ax_x.set_ylabel(' Meters', labelpad=15) ax_x.yaxis.set_label_position("right") ax_x.spines['right'].set_bounds(0, -30) # Plot the hydro df_hydro = read_fsb_hydro(hydro_path) pq_axes = plot_fsb_hydro(df_hydro, axes=ax_hydro) # Add 1 hour to Swiss local winter time pq_axes[0].axvline(x=time, linestyle=':', color='k', linewidth=2.) pq_axes[0].set_xlabel('Time', fontsize=14) return fig
def candlestick2(ax, opens, closes, highs, lows, width=4, colorup='k', colordown='r', alpha=0.75, ): """ Represent the open, close as a bar line and high low range as a vertical line. ax : an Axes instance to plot to width : the bar width in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open alpha : bar transparency return value is lineCollection, barCollection """ # note this code assumes if any value open, close, low, high is # missing they all are missing delta = width/2. barVerts = [ ( (i-delta, open), (i-delta, close), (i+delta, close), (i+delta, open) ) for i, open, close in zip(xrange(len(opens)), opens, closes) if open != -1 and close!=-1 ] rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1 ] r,g,b = colorConverter.to_rgb(colorup) colorup = r,g,b,alpha r,g,b = colorConverter.to_rgb(colordown) colordown = r,g,b,alpha colord = { True : colorup, False : colordown, } colors = [colord[open<close] for open, close in zip(opens, closes) if open!=-1 and close !=-1] assert(len(barVerts)==len(rangeSegments)) useAA = 0, # use tuple here lw = 0.5, # and here rangeCollection = LineCollection(rangeSegments, colors = ( (0,0,0,1), ), linewidths = lw, antialiaseds = useAA, ) barCollection = PolyCollection(barVerts, facecolors = colors, edgecolors = ( (0,0,0,1), ), antialiaseds = useAA, linewidths = lw, ) minx, maxx = 0, len(rangeSegments) miny = min([low for low in lows if low !=-1]) maxy = max([high for high in highs if high != -1]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(barCollection) ax.add_collection(rangeCollection) return rangeCollection, barCollection
def _create_xvy_trajectory_fig(self, filter_index, week_index, x_index, y_index, feature_name): ### Generate features subject_generator = self.subject.get_full_generator() features, labels = next(subject_generator) ### Create figure fig, axs = plt.subplots(1) fig.set_figwidth(self.save_config.Callback.figwidth) fig.set_figheight(self.save_config.Callback.figheight) fig.tight_layout() fig.suptitle("Week " + str(week_index + 1) + " Trajectory Response: X vs Y") ### Get individual points x_points = features[0, week_index, :, x_index] y_points = features[0, week_index, :, y_index] ### Create combined points and segments points = np.array([x_points, y_points]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) ### Get convolutional output from logs conv_output = self.recent_epoch_logs["convolutional_output"] ### Define colormap function norm = plt.Normalize(conv_output[0, week_index, :, filter_index].min(), conv_output[0, week_index, :, filter_index].max()) lc = LineCollection(segments, cmap='viridis', norm=norm) # Set the values used for colormapping lc.set_array(conv_output[0, week_index, :, filter_index]) lc.set_linewidth(2) line = axs.add_collection(lc) fig.colorbar(line, ax=axs) ### Set margins margin = .3 half_x_points = x_points.max() - (x_points.min() + x_points.max()) / 2 axs.set_xlim(x_points.min() - half_x_points * margin, x_points.max() + half_x_points * margin) half_y_points = y_points.max() - (y_points.min() + y_points.max()) / 2 axs.set_ylim(y_points.min() - half_y_points * margin, y_points.max() + half_y_points * margin) ### Set labels axs.set_xlabel("Y Position") axs.set_ylabel("X Position") ### Save filter response fig as png and eps filter_response_folder_path = "results/" + self.save_config.Output.batch_name + "/" + self.child_name + "/trajectory-responses/" if not os.path.exists(filter_response_folder_path): os.mkdir(filter_response_folder_path) filter_response_folder_path += "{}/".format(feature_name) if not os.path.exists(filter_response_folder_path): os.mkdir(filter_response_folder_path) filter_response_folder_path += "x-vs-y/".format(filter_index) if not os.path.exists(filter_response_folder_path): os.mkdir(filter_response_folder_path) filter_response_folder_path += "filter-{}/".format(filter_index) if not os.path.exists(filter_response_folder_path): os.mkdir(filter_response_folder_path) filter_response_folder_path += "week-{}/".format(week_index + 1) if not os.path.exists(filter_response_folder_path): os.mkdir(filter_response_folder_path) single_response_png_path = filter_response_folder_path + "week-{}.png".format( week_index + 1) fig.savefig(single_response_png_path, dpi=200, format="png", bbox_inches="tight") single_response_eps_path = filter_response_folder_path + "week-{}.eps".format( week_index + 1) fig.savefig(single_response_eps_path, dpi=200, format="eps", bbox_inches="tight") plt.close(fig)
def create_histogram(dst, name, pw_start_time, call_status, cos_config): runtime_bins = np.linspace(0, 600, 600) def compute_times_rates(time_rates): x = np.array(time_rates) #tzero = np.min(x[:, 0]) tzero = pw_start_time start_time = x[:, 0] - tzero end_time = x[:, 1] - tzero N = len(start_time) runtime_calls_hist = np.zeros((N, len(runtime_bins))) for i in range(N): s = start_time[i] e = end_time[i] a, b = np.searchsorted(runtime_bins, [s, e]) if b - a > 0: runtime_calls_hist[i, a:b] = 1 return { 'start_time': start_time, 'end_time': end_time, 'runtime_calls_hist': runtime_calls_hist } fig = pylab.figure(figsize=(10, 6)) ax = fig.add_subplot(1, 1, 1) time_rates = [(rs['start_time'], rs['end_time']) for rs in call_status] time_hist = compute_times_rates(time_rates) N = len(time_hist['start_time']) line_segments = LineCollection( [[[time_hist['start_time'][i], i], [time_hist['end_time'][i], i]] for i in range(N)], linestyles='solid', color='k', alpha=0.6, linewidth=0.4) ax.add_collection(line_segments) ax.plot(runtime_bins, time_hist['runtime_calls_hist'].sum(axis=0), label='Total Active Calls', zorder=-1) #ax.set_xlim(0, x_lim) ax.set_xlim(0, np.max(time_hist['end_time']) * 3) ax.set_ylim(0, len(time_hist['start_time']) * 1.05) ax.set_xlabel("Execution Time (sec)") ax.set_ylabel("Function Call") ax.grid(False) ax.legend(loc='upper right') fig.tight_layout() if dst.split('://')[0] == 'cos': save_plot_in_cos(cos_config, fig, dst, name + "_histogram.png") else: fig.savefig(os.path.join(dst, name + "_histogram.png")) pylab.close(fig)
def create_ngram_plot(term_or_topic_list: list, use_log_scale: bool = False, subplot_ax: Subplot = None, plot_title: str = None, plot_filename: str = None, show_plot: bool = False, show_male_female_bar: bool = None, scale_factor: int = 1, master_viz_data: dict = None): print(f'Drawing ngram plot for {term_or_topic_list}') if subplot_ax and plot_filename: raise ValueError( "Cannot save a plot that will be stored in a subplot.") if show_male_female_bar not in [None, 'horizontal', 'vertical']: raise ValueError( "show_male_female_bar has to be None, horizontal, or vertical.") if term_or_topic_list[0].startswith( 'topic.') or term_or_topic_list[0].startswith('gen_approach_'): mode = 'topics' else: mode = 'terms' if not master_viz_data: master_viz_data = load_master_viz_data(mode) data = {term: master_viz_data[term] for term in term_or_topic_list} start_year = next(iter(data.values()))['year'][0] end_year = next(iter(data.values()))['year'][0] # 2: Set up the plot # if an ax is passed, we're creating a subplot for that axes. otherwise, we're creating a # complete plot here. if subplot_ax is None: fig = plt.figure(figsize=(12, 12)) gs = gridspec.GridSpec(nrows=1, ncols=1, figure=fig, width_ratios=[1], height_ratios=[1], wspace=0.2, hspace=0.05) ax = fig.add_subplot(gs[0, 0]) else: ax = subplot_ax ax.set_ylim(0, 1) ax.set_xlim(start_year + 2, end_year - 2) ax.set_axisbelow(True) ax.grid(which='major', axis='both') # add all passed terms to chart for t in term_or_topic_list: x = data[t]['year'] y = data[t]['freq'] freq_scores = data[t]['freq_score'] x_lin = np.linspace(min(data[t]['year']), max(data[t]['year']), 1000) spl = make_interp_spline(x, y, k=2) y_lin = spl(x_lin) spl_freq_score = make_interp_spline(x, freq_scores, k=1) freq_score_lin = spl_freq_score(x_lin) points = np.array([x_lin, y_lin]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) norm = plt.Normalize(0.0, 1.0) lc = LineCollection(segments, cmap='coolwarm', norm=norm) # Set the values used for colormapping lc.set_array(freq_score_lin) lc.set_linewidth(4 * scale_factor) line = ax.add_collection(lc) # Line below can be used to add a label to the right of the frequency line # ax.text(x=max(x)+1, y=y[-1], s=t, fontsize=14) # Set x axis (years) ax.set_xlim(x_lin.min(), x_lin.max()) ax.tick_params(axis='x', labelsize=14 * scale_factor) # Set y axis (frequencies or topic weights) y_max = max([max(data[t]['freq']) for t in term_or_topic_list]) * 1.2 ax.set_ylim(0, y_max) ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1.0)) if use_log_scale: y_min = min([min(data[t]['freq']) for t in term_or_topic_list]) * 1.2 ax.set_yscale('log') ax.tick_params(axis='y', labelsize=14 * scale_factor) # Set title if plot_title: ax.set_title(label=plot_title, weight='bold', fontsize=24 * scale_factor, pad=20 * scale_factor) # Set color bar with male female indicator if show_male_female_bar: fig.colorbar(line, ax=ax, orientation=show_male_female_bar, fraction=0.1) if plot_filename: plt.savefig( Path(BASE_PATH, 'visualizations', 'ngram_plots', plot_filename)) if show_plot: plt.show() if subplot_ax: return ax
(1, '#1C76BC')], N=256) fig, axs = plt.subplots(1, 1, figsize=(7, 7)) axs.margins(y=0, x=0) x = np.linspace(0.1, 0.9, num=9) y = np.mean(environmentLacunarities, axis=0) yq75, yq25 = np.percentile(environmentLacunarities, [75, 25], axis=0) colors = cmap(y / np.max(y)) axs.scatter(x, y, c=colors, edgecolor='none') points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=cmap) lc.set_array(y) lc.set_linewidth(1.5) axs.add_collection(lc) axs.errorbar(x[:3], y[:3], yerr=[(y[:3] - yq25[:3]).tolist(), (yq75[:3] - y[:3]).tolist()], fmt='none', ecolor='#1C76BC') axs.errorbar(x[3:7], y[3:7], yerr=[(y[3:7] - yq25[3:7]).tolist(), (yq75[3:7] - y[3:7]).tolist()], fmt='none',
def plot_band_weight( kslist, ekslist, wkslist=None, efermi=None, shift_efermi=False, yrange=None, output=None, style="alpha", color="blue", axis=None, width=10, fatness=4, xticks=None, cmap=mpl.cm.bwr, weight_min=-0.1, weight_max=0.6, ): if axis is None: fig, a = plt.subplots() else: a = axis if efermi is not None and shift_efermi: ekslist = np.array(ekslist) - efermi else: ekslist = np.array(ekslist) xmax = max(kslist[0]) if yrange is None: yrange = ( np.array(ekslist).flatten().min() - 0.66, np.array(ekslist).flatten().max() + 0.66, ) if wkslist is not None: for i in range(len(kslist)): x = kslist[i] y = ekslist[i] # lwidths=np.ones(len(x)) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) if style == "width": lwidths = np.array(wkslist[i]) * width lc = LineCollection(segments, linewidths=lwidths, colors=color) elif style == "alpha": lwidths = np.array(wkslist[i]) * width # The alpha values sometimes goes above 1 so in those cases we will normalize # the alpha values. -Uthpala alpha_values = [lwidth / (width + 0.05) for lwidth in lwidths] if max(alpha_values) > 1: print("alpha is larger than 1. Renormalizing values.") alpha_values = [ alpha_i / max(alpha_values) for alpha_i in alpha_values ] lc = LineCollection( segments, linewidths=[fatness] * len(x), colors=[ colorConverter.to_rgba(color, alpha=alpha_i) for alpha_i in alpha_values ], ) elif style == "color" or style == "colormap": lwidths = np.array(wkslist[i]) * width norm = mpl.colors.Normalize(vmin=weight_min, vmax=weight_max) # norm = mpl.colors.SymLogNorm(linthresh=0.03,vmin=weight_min, vmax=weight_max) m = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) # lc = LineCollection(segments,linewidths=np.abs(norm(lwidths)-0.5)*1, colors=[m.to_rgba(lwidth) for lwidth in lwidths]) lc = LineCollection( segments, linewidths=lwidths, colors=[m.to_rgba(lwidth) for lwidth in lwidths], ) a.add_collection(lc) if axis is None: for ks, eks in zip(kslist, ekslist): a.plot(ks, eks, color="gray", linewidth=0.01) # a.set_xlim(0, xmax) # a.set_ylim(yrange) if xticks is not None: a.set_xticks(xticks[1]) a.set_xticklabels(xticks[0]) for x in xticks[1]: a.axvline(x, alpha=0.6, color="black", linewidth=0.7) if efermi is not None: if shift_efermi: a.axhline(linestyle="--", color="black") else: a.axhline(efermi, linestyle="--", color="black") return a
def plot_pathline(self, pl, travel_time=None, **kwargs): """ Plot the MODPATH pathlines. Parameters ---------- pl : list of rec arrays or a single rec array rec array or list of rec arrays is data returned from modpathfile PathlineFile get_data() or get_alldata() methods. Data in rec array is 'x', 'y', 'z', 'time', 'k', and 'particleid'. travel_time: float or str travel_time is a travel time selection for the displayed pathlines. If a float is passed then pathlines with times less than or equal to the passed time are plotted. If a string is passed a variety logical constraints can be added in front of a time value to select pathlines for a select period of time. Valid logical constraints are <=, <, >=, and >. For example, to select all pathlines less than 10000 days travel_time='< 10000' would be passed to plot_pathline. (default is None) kwargs : layer, ax, colors. The remaining kwargs are passed into the LineCollection constructor. If layer='all', pathlines are output for all layers Returns ------- lc : matplotlib.collections.LineCollection """ from matplotlib.collections import LineCollection # make sure pathlines is a list if not isinstance(pl, list): pl = [pl] if 'layer' in kwargs: kon = kwargs.pop('layer') if sys.version_info[0] > 2: if isinstance(kon, bytes): kon = kon.decode() if isinstance(kon, str): if kon.lower() == 'all': kon = -1 else: kon = self.layer else: kon = self.layer if 'ax' in kwargs: ax = kwargs.pop('ax') else: ax = self.ax if 'colors' not in kwargs: kwargs['colors'] = '0.5' linecol = [] for p in pl: if travel_time is None: tp = p.copy() else: if isinstance(travel_time, str): if '<=' in travel_time: time = float(travel_time.replace('<=', '')) idx = (p['time'] <= time) elif '<' in travel_time: time = float(travel_time.replace('<', '')) idx = (p['time'] < time) elif '>=' in travel_time: time = float(travel_time.replace('>=', '')) idx = (p['time'] >= time) elif '<' in travel_time: time = float(travel_time.replace('>', '')) idx = (p['time'] > time) else: try: time = float(travel_time) idx = (p['time'] <= time) except: errmsg = 'flopy.map.plot_pathline travel_time ' + \ 'variable cannot be parsed. ' + \ 'Acceptable logical variables are , ' + \ '<=, <, >=, and >. ' + \ 'You passed {}'.format(travel_time) raise Exception(errmsg) else: time = float(travel_time) idx = (p['time'] <= time) tp = p[idx] vlc = [] # rotate data x0r, y0r = self.sr.rotate(tp['x'], tp['y'], self.sr.rotation, 0., self.sr.yedge[0]) x0r += self.sr.xul y0r += self.sr.yul - self.sr.yedge[0] # build polyline array arr = np.vstack((x0r, y0r)).T # select based on layer if kon >= 0: kk = p['k'].copy().reshape(p.shape[0], 1) kk = np.repeat(kk, 2, axis=1) arr = np.ma.masked_where((kk != kon), arr) else: arr = np.ma.asarray(arr) # append line to linecol if there is some unmasked segment if not arr.mask.all(): linecol.append(arr) # create line collection lc = None if len(linecol) > 0: lc = LineCollection(linecol, **kwargs) ax.add_collection(lc) return lc
def make_sub_ax_grid(sub_ax, l): if l > 0: # Vertical lines. seg_x = np.zeros(((l + 1), 2)) seg_y = np.zeros(((l + 1), 2)) segs = np.zeros(((l + 1), 2, 2)) seg_x[:, 0] = seg_x[:, 0] + (2.0 * np.array(range(1, l + 2))) seg_x[:, 1] = seg_x[:, 0] seg_y[:, 0] = 0.0 seg_y[:, 1] = 4.0 segs[:, :, 0] = seg_x segs[:, :, 1] = seg_y segs_vert = segs # Horizontal lines. seg_x = np.zeros((3, 2)) seg_y = np.zeros((3, 2)) segs = np.zeros((3, 2, 2)) seg_x[:, 0] = 2.0 seg_x[:, 1] = 2.0*(l + 1.0) seg_y[:, 0] = [0.0, 2.0, 4.0] seg_y[:, 1] = seg_y[:, 0] segs[:, :, 0] = seg_x segs[:, :, 1] = seg_y segs_horz = segs # Box at start. seg_x = np.zeros((3, 2)) set_y = np.zeros((3, 2)) segs = np.zeros((3, 2, 2)) seg_x[0, :] = [0.0, 2.0] # Top. seg_y[0, :] = [3.0, 3.0] seg_x[1, :] = [0.0, 2.0] # Bottom. seg_y[1, :] = [1.0, 1.0] seg_x[2, :] = [0.0, 0.0] # Left. seg_y[2, :] = [1.0, 3.0] segs[:, :, 0] = seg_x segs[:, :, 1] = seg_y segs_box = segs # segs = np.concatenate([segs_vert, segs_horz, segs_box]) else: # Box at start. seg_x = np.zeros((4, 2)) seg_y = np.zeros((4, 2)) segs = np.zeros((4, 2, 2)) seg_x[0, :] = [0.0, 2.0] # Top. seg_y[0, :] = [3.0, 3.0] seg_x[1, :] = [0.0, 2.0] # Bottom. seg_y[1, :] = [1.0, 1.0] seg_x[2, :] = [0.0, 0.0] # Left. seg_y[2, :] = [1.0, 3.0] seg_x[3, :] = [2.0, 2.0] # Right. seg_y[3, :] = [1.0, 3.0] segs[:, :, 0] = seg_x segs[:, :, 1] = seg_y # line_segments = LineCollection(segs, colors = 'k', clip_on = False) sub_ax.add_collection(line_segments) return
def plot(self, **kwargs): if len(self.edges) > 0: edges = self.X[self.edges] coll = LineCollection(edges) gca().add_collection(coll) field.XYZField.plot(self, **kwargs)
def graph_smile_formula_bond_pairs(s, xs, ys, position): cm = plt.get_cmap("RdYlGn") mkdir('graphs') label = ''.join(['Smile Formula Graph: ', s]) zeros = [0.0 for x in xs] complete_set = [xs[0]] complete_set.extend(ys) complete_position = [0] complete_position.extend(position) complete_zeros = [0.0] complete_zeros.extend(zeros) for graph_type in ['scatter', 'line']: #line if graph_type == 'line': # convert to ndarray xs = array(xs) ys = array(ys) position = array(position) points = np.array([xs, ys]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) #print('segments', segments.shape) fig, axs = plt.subplots(2, 1, sharex=True, sharey=True) norm = plt.Normalize(0, position.max()) lc = LineCollection(segments, cmap='viridis', norm=norm) lc.set_array(position) lc.set_linewidth(2) line = axs[0].add_collection(lc) fig.colorbar(line, ax=axs[0]) axs[0].set_xlim(0, xs.max()) axs[0].set_ylim(0, ys.max()) fig.delaxes(axs[1]) #plt.show() image_path = ''.join(['graphs/', s, '_', graph_type, '.png']) plt.savefig(image_path) plt.close() elif graph_type == 'scatter': colors = [cm(float(i) / len(zeros)) for i in range(len(zeros))] complete_colors = [ cm(float(i) / len(complete_zeros)) for i in range(len(complete_zeros)) ] image_path = ''.join(['graphs/', s, '_', graph_type, '.png']) scatters = { 'default': { 'xs': xs, 'ys': ys, 'zs': zeros, 'colors': colors, 'xlabel': '1st electron count', 'ylabel': '2nd electron count', 'zlabel': 'N/A', 'title': 'Bond Pair Electron Counts', 'path': ''.join(['graphs/', s, '_default_', graph_type, '.png']) }, 'position': { 'xs': complete_position, 'ys': complete_set, 'zs': complete_zeros, 'colors': complete_colors, 'xlabel': 'Position of element', 'ylabel': 'Electron count', 'zlabel': 'N/A', 'title': 'Electron counts by position in smile formula', 'path': ''.join(['graphs/', s, '_position_', graph_type, '.png']) }, 'all': { 'xs': xs, 'ys': ys, 'zs': position, 'colors': colors, 'xlabel': '', 'ylabel': '', 'zlabel': '', 'title': '', 'path': ''.join(['graphs/', s, '_all_', graph_type, '.png']) } } for scatter, value in scatters.items(): make_plot(value, cm) plt.close() ''' # comment in one of the following sections if you want to use plotly which has a nice browser UI default = go.Scatter3d(x=xs, y=ys, z=zeros) if graph_type == 'scatter' else px.line_3d(x=xs, y=ys, z=zeros) change = go.Scatter3d(x=complete_position, y=complete_set, z=zeros) if graph_type == 'scatter' else px.line_3d(x=complete_position, y=complete_set, z=zeros) all_changes = go.Scatter3d(x=xs, y=ys, z=position) if graph_type == 'scatter' else px.line_3d(x=xs, y=ys, z=position) fig = go.Figure() fig.add_trace(default) fig.add_trace(change) fig.add_trace(all_changes) fig.update_layout(title = label) fig.show() # comment in the following section if youre using plotly & working offline to view graph in the browser plotly.offline.plot( { "data": traces, "layout": go.Layout(title=label) }, image='jpeg', image_filename=image_path ) traces = [default, change, all_changes] py.image.save_as({'data':traces}, image_path, format='png') ''' return True
axa.set_ylabel('$y$') axa.set_title('Double Pendulum') line1, = axa.plot([0, x1[0]], [0, y1[0]], ':', color='gray', zorder=-1, alpha=0.5) dot1, = axa.plot(x1[0], y1[0], '.', color='gray', markersize=15, zorder=1) trace1, = axa.plot(x1[:0], y1[:0], color='gray', linewidth=0.75, alpha=0.5) line2, = axa.plot([x1[0], x2[0]], [y1[0], y2[0]], 'k:', zorder=-1, alpha=0.5) dot2, = axa.plot(x2[0], y2[0], 'k.', markersize=15, zorder=1) verts = list(zip(x2, y2)) segs = [[verts[i], verts[i + 1]] for i in range(len(verts) - 1)] trace2 = LineCollection(segs) colors = full((len(x1), ), 'none') trace2.set_color(colors) trace2.set_alpha(0.8) axa.add_collection(trace2) axb = plt.subplot2grid((2, 4), (0, 2), colspan=2, rowspan=1) axb.set_xlim(-0.01 * t.max(), 1.01 * t.max()) axb.set_ylim(min(t1) * 1.01, max(t1) * 1.01) axb.set_ylabel(r'$\theta_1$') th1, = axb.plot([], [], color='gray') axc = plt.subplot2grid((2, 4), (1, 2), colspan=2, rowspan=1) axc.set_xlim(-0.01 * t.max(), 1.01 * t.max()) axc.set_ylim(min(t2) * 1.01, max(t2) * 1.01) axc.set_ylabel(r'$\theta_2$')
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=None, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, **kwds): """Draw the edges of the graph G This draws only the edges of the graph G. pos is a dictionary keyed by vertex with a two-tuple of x-y positions as the value. See networkx.layout for functions that compute node positions. edgelist is an optional list of the edges in G to be drawn. If provided, only the edges in edgelist will be drawn. edgecolor can be a list of matplotlib color letters such as 'k' or 'b' that lists the color of each edge; the list must be ordered in the same way as the edge list. Alternatively, this list can contain numbers and those number are mapped to a color scale using the color map edge_cmap. Finally, it can also be a list of (r,g,b) or (r,g,b,a) tuples, in which case these will be used directly to color the edges. If the latter mode is used, you should not provide a value for alpha, as it would be applied globally to all lines. For directed graphs, 'arrows' (actually just thicker stubs) are drawn at the head end. Arrows can be turned off with keyword arrows=False. See draw_networkx for the list of other optional parameters. """ try: import matplotlib.pylab as pylab import matplotlib.cbook as cb from matplotlib.colors import colorConverter, Colormap from matplotlib.collections import LineCollection except ImportError: raise ImportError("Matplotlib required for draw()") except RuntimeError: pass # unable to open display if ax is None: ax = pylab.gca() if edgelist is None: edgelist = G.edges() if not edgelist or len(edgelist) == 0: # no edges! return None # set edge positions edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) if not cb.iterable(width): lw = (width, ) else: lw = width if not cb.is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color) == len(edge_pos): if np.alltrue([cb.is_string_like(c) for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple( [colorConverter.to_rgba(c, alpha) for c in edge_color]) elif np.alltrue([not cb.is_string_like(c) for c in edge_color]): # If color specs are given as (rgb) or (rgba) tuples, we're OK if np.alltrue( [cb.iterable(c) and len(c) in (3, 4) for c in edge_color]): edge_colors = tuple(edge_color) alpha = None else: # numbers (which are going to be mapped with a colormap) edge_colors = None else: e_s = 'edge_color must consist of either color names or numbers' raise ValueError(e_s) else: if len(edge_color) == 1: edge_colors = (colorConverter.to_rgba(edge_color, alpha), ) else: e_s = 'edge_color must be a single color or list of exactly' e_s += 'm colors where m is the number or edges' raise ValueError(e_s) edge_collection = LineCollection( edge_pos, colors=edge_colors, linewidths=lw, antialiaseds=(1, ), linestyle=style, transOffset=ax.transData, ) # Note: there was a bug in mpl regarding the handling of alpha values for # each line in a LineCollection. It was fixed in matplotlib in r7184 and # r7189 (June 6 2009). We should then not set the alpha value globally, # since the user can instead provide per-edge alphas now. Only set it # globally if provided as a scalar. if cb.is_numlike(alpha): edge_collection.set_alpha(alpha) # need 0.87.7 or greater for edge colormaps if edge_colors is None: if edge_cmap is not None: assert (isinstance(edge_cmap, Colormap)) edge_collection.set_array(np.asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() pylab.sci(edge_collection) # else: # sys.stderr.write(\ # """matplotlib version >= 0.87.7 required for colormapped edges. # (version %s detected)."""%matplotlib.__version__) # raise UserWarning(\ # """matplotlib version >= 0.87.7 required for colormapped edges. # (version %s detected)."""%matplotlib.__version__) arrow_collection = None if G.is_directed() and arrows: # a directed graph hack # draw thick line segments at head end of edge # waiting for someone else to implement arrows that will work arrow_colors = (colorConverter.to_rgba('k', alpha), ) a_pos = [] p = 1.0 - 0.25 # make head segment 25 percent of edge length for src, dst in edge_pos: x1, y1 = src x2, y2 = dst dx = x2 - x1 # x offset dy = y2 - y1 # y offset d = np.sqrt(float(dx**2 + dy**2)) # length of edge if d == 0: # source and target at same position continue if dx == 0: # vertical edge xa = x2 ya = dy * p + y1 if dy == 0: # horizontal edge ya = y2 xa = dx * p + x1 else: theta = np.arctan2(dy, dx) xa = p * d * np.cos(theta) + x1 ya = p * d * np.sin(theta) + y1 a_pos.append(((xa, ya), (x2, y2))) arrow_collection = LineCollection( a_pos, colors=arrow_colors, linewidths=[4 * ww for ww in lw], antialiaseds=(1, ), transOffset=ax.transData, ) # update view minx = np.amin(np.ravel(edge_pos[:, :, 0])) maxx = np.amax(np.ravel(edge_pos[:, :, 0])) miny = np.amin(np.ravel(edge_pos[:, :, 1])) maxy = np.amax(np.ravel(edge_pos[:, :, 1])) w = maxx - minx h = maxy - miny padx, pady = 0.05 * w, 0.05 * h corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady) ax.update_datalim(corners) ax.autoscale_view() edge_collection.set_zorder(1) # edges go behind nodes ax.add_collection(edge_collection) if arrow_collection: arrow_collection.set_zorder(1) # edges go behind nodes ax.add_collection(arrow_collection) return ax