def plot_spectral_points(self, spectra, fmt='r+', labels=None, lpos=None): ''' Plots spectral profiles in feature space. ''' m, n, c = self.__dims__ assert type(spectra) in ( list, tuple, np.ndarray), 'Expected spectra to be a list, tuple, or numpy array' if labels is not None and lpos is None: lpos = [(30, -30)] * len(labels) for i, spec in enumerate(spectra): plt.plot(spec[m], spec[n], fmt, ms=20, mew=2) if labels is not None: xy = (spec[m], spec[n]) plt.annotate(labels[i], xy=xy, xytext=lpos[i], textcoords='offset points', ha='right', va='bottom', fontsize=14, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
def plot_xy_points(self, coords, fmt='r+', labels=None, lpos=None, dd=True): ''' Add point(s) to the plot, given by their longitude-latitude (XY) coordinates, which will be displayed at the appropriate feature space coordinates. ''' assert not self.__raveled__, 'Cannot do this when the input array is raveled' m, n, c = self.__dims__ pcoords = xy_to_pixel(coords, gt=self.__gt__, wkt=self.__wkt__, dd=dd) if labels is not None and lpos is None: lpos = [(10, -10)] * len(labels) # http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot for i, (x, y) in enumerate(pcoords): spec = self.features[x, y, :] plt.plot(spec[m], spec[n], fmt, ms=20, mew=2) if labels is not None: plt.annotate(labels[i], xy=(spec[m], spec[n]), xytext=lpos[i], textcoords='offset points', ha='right', va='bottom', fontsize=14, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
def plot_profits(self, player, period): profits = self.results["profits"][-period:] plt.title("Profits") time_window = 100 x = np.arange(len(profits[:, player])) y = [] for i in x: if i < time_window: y_value = np.mean(profits[:i + 1, player]) else: y_value = np.mean(profits[i - time_window:i + 1, player]) y.append(y_value) plt.plot(x, y, color="black") maximum_profit = \ self.parameters["n_positions"] * \ self.parameters["n_prices"] plt.ylim(0, maximum_profit) plt.annotate("Time window: {}".format(time_window), xy=(0.8, 0.1), xycoords='axes fraction', fontsize=6) # plt.annotate(self.string_parameters, xy=(-0.05, -0.1), xycoords='axes fraction', fontsize=6) plt.savefig(self.format_fig_name("profits_player{}".format(player))) plt.close()
def biaozhukedu(dfc, weibiao): if weibiao == dfc.index.max(): kedus = [dfc.loc[weibiao]] else: kedus = [dfc.loc[weibiao], dfc.loc[dfc.index.max()]] # print(type(kedus[0])) for ii in range(len(kedus)): kedu = kedus[ii] if (len(dfc.index)) > 12: idx = kedu.name else: idx = list(dfc.index).index(kedu.name) if not np.isnan(kedu.iloc[0]): plt.plot([idx, idx], [0, kedu.iloc[0]], 'c--') plt.annotate(str(kedu.name), xy=(idx, 0), xycoords='data', xytext=(-20, -20), textcoords='offset points', color='r', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0")) for i in range(len(kedu)): if np.isnan(kedu.iloc[i]): # print(kedu.iloc[i]) # print(type(kedu.iloc[i])) continue plt.scatter([ idx, ], [kedu.iloc[i]], 50, color='Wheat') # global ywananchor if kedu.map(lambda x: abs(x)).max() >= ywananchor: kedubiaozhi = "%.1f万" % (kedu.iloc[i] / 10000) plt.gca().yaxis.set_major_formatter( FuncFormatter(lambda x, pos: "%d万" % int(x / 10000)) ) # 纵轴主刻度文本用y_formatter函数计算 else: kedubiaozhi = "%d" % kedu.iloc[i] fontsize = 8 if (i % 2) == 0: zhengfu = -1 else: zhengfu = 0.4 plt.annotate( kedubiaozhi, xy=(idx, kedu.iloc[i]), xycoords='data', xytext=(len(kedubiaozhi) * fontsize * zhengfu, int(len(kedubiaozhi) * fontsize * (-1) * zhengfu / 2)), textcoords='offset points', fontsize=fontsize, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", color='Purple'))
def add_data(self, income, grade, color='yellow', markersize=25, markertext=None): """Add a value and plot it""" self.incomes.append(income) self.grades.append(grade) plt.plot([income], [grade], color=color, marker='o', markersize=markersize) if markertext: plt.annotate(markertext, xy=(income, grade), horizontalalignment='center', verticalalignment='center')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show() '===========================================' ax = plt.subplot(111) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2 * np.pi * t) line, = plt.plot(t, s, lw=2) plt.annotate( 'local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), ) plt.ylim(-2, 2) plt.show() '===========================================' # 导入 matplotlib 的所有内容(nympy 可以用 np 这个名字来使用) # 创建一个 8 * 6 点(point)的图,并设置分辨率为 80 figure(figsize=(8, 6), dpi=80) # 创建一个新的 1 * 1 的子图,接下来的图样绘制在其中的第 1 块(也是唯一的一块) subplot(1, 1, 1)
del expr S_T = S_BM[ -1 ] mu_3s = np.mean( S_T ) + 3 * np.std( S_T ) mu_5s = np.mean( S_T ) + 5 * np.std( S_T ) #............................................................................ # Histogram of final values #............................................................................ plt.hist( S_T, bins = 100, edgecolor = 'darkgray', color = 'darkblue' ) plt.axvline( S0, linestyle = 'dashed', alpha = 0.8, color = 'darkred' ) plt.axvline( np.mean( S_T ) , linestyle = 'dashed', alpha = 0.8, color = 'red' ) plt.axvline( mu_3s, linestyle = 'dashed', alpha = 0.8, color = 'red' ) plt.annotate( s = '$\mu + 3\sigma = $' + str( round( mu_3s ,1) ), xy=(mu_3s, 500 ) ) plt.axvline( mu_5s, linestyle = 'dashed', alpha = 0.8, color = 'red' ) plt.annotate( s = '$\mu + 5\sigma = $' + str( round( mu_5s ,1) ), xy=(mu_5s, 500 ) ) plt.xlabel('index level' ) plt.ylabel('frequency' ) plt.title( 'Geometric Brownian Motion: distribution of $S_T$' ) #............................................................................ # Sample of paths #............................................................................ plt.plot( S_BM[:, :10], lw = 0.85, linestyle = '-.' ) plt.xlabel('time') plt.xlabel('index level')
def getcutpoint(inputdatapath): """ 根据时间间隔找到分割点,生成最近一次的图像和全部综合图像并返回 """ totalmen = gettotalmem(getdatapath(inputdatapath)) inputdf = getdatadf(getdatapath(inputdatapath)) ds = inputdf['time'] - inputdf['time'].shift() deltads = ds[ds > getdelta()] outlst = list() for ix in deltads.index: ipos = list(inputdf.index).index(ix) # 处理内存占满(但未重启)的特殊情况 if inputdf.iloc[ipos - 1]['freeper'] == 0: continue print() print(ipos, ix, deltads[ix]) outlst.append(ipos) # bfdf = inputdf[inputdf.index >= (ix - deltads[ix] + pd.Timedelta(minutes=-5))] # tmpdf = bfdf[bfdf.index < (ix + pd.Timedelta(minutes=5))] # print(tmpdf) outlst.insert(0, 0) outlst.append(inputdf.shape[0]) plt.rcParams['font.sans-serif'] = 'SimHei' olen = len(outlst) if olen == 2: picheight = 1 elif olen == 3: picheight = 2 else: picheight = 3 plt.figure(figsize=(10, 10 * picheight)) imgpath = getdirmain() / 'img' / 'freemen.png' touchfilepath2depth(imgpath) # fig, ax1 = plt.subplots() # 针对数据集周期次数进行处理,主要是处理小于三次的情况 if len(outlst) > 3: plt.subplot(311) elif len(outlst) == 3: plt.subplot(211) # 最近数据集图形化输出 plt.ylabel(f'空闲内存百分比({totalmen}G)') cutdf = inputdf.iloc[outlst[-2]:outlst[-1]] plt.plot(cutdf.index, cutdf['freeper']) plt.ylim(0, 100) plt.title('最近一次运行') plt.annotate(cutdf.index[0].strftime("%y-%m-%d %H:%M"), xy=[cutdf.index[0], cutdf.iloc[0, 1]]) plt.annotate(cutdf.index[-1].strftime("%y-%m-%d %H:%M"), xy=[cutdf.index[-1], cutdf.iloc[-1, 1]]) # 针对单次(一般也是首次运行)数据集进行处理 if len(outlst) == 2: plt.savefig(imgpath) return str(imgpath) # 针对数据集周期次数进行处理,主要是处理小于三次的情况 if len(outlst) == 3: plt.subplot(212) elif len(outlst) > 3: plt.subplot(312) plt.ylabel(f'空闲内存百分比({totalmen}G)') plt.ylim(0, 100) plt.title('最近两次运行') twolst = outlst[-3:] for i in range(len(twolst) - 1): cutdf = inputdf.iloc[twolst[i]:twolst[i + 1]] plt.plot(cutdf.index, cutdf['freeper']) plt.annotate(cutdf.index[0].strftime("%y-%m-%d %H:%M"), xy=[cutdf.index[0], cutdf.iloc[0, 1]]) plt.annotate(cutdf.index[-1].strftime("%y-%m-%d %H:%M"), xy=[cutdf.index[-1], cutdf.iloc[-1, 1]]) # 综合(全部)数据集图形输出 # 针对仅有两次数据集进行处理 if len(outlst) == 3: plt.savefig(imgpath) return str(imgpath) else: plt.subplot(313) plt.ylabel(f'空闲内存百分比({totalmen}G)') plt.ylim(0, 100) plt.title('历次运行') for i in range(len(outlst) - 1): cutdf = inputdf.iloc[outlst[i]:outlst[i + 1]] plt.plot(cutdf.index, cutdf['freeper']) plt.annotate(cutdf.index[0].strftime("%y-%m-%d %H:%M"), xy=[cutdf.index[0], cutdf.iloc[0, 1]]) plt.annotate(cutdf.index[-1].strftime("%y-%m-%d %H:%M"), xy=[cutdf.index[-1], cutdf.iloc[-1, 1]]) plt.savefig(imgpath) return str(imgpath)