def __init__(self, parent=None): super(Example2, self).__init__(parent) figure1 = plt.figure(1) # 返回当前的figure x = [1, 2, 3] y = [4, 5, 6] plt.plot(x, y) plt.title('Example1') plt.xlabel('x') plt.ylabel('y') figure2 = plt.figure(2) # 返回当前的figure x = [7, 8, 9] y = [4, 5, 6] plt.plot(x, y) plt.title('Example2') plt.xlabel('x') plt.ylabel('y') self.canvas1 = figureCanvas(figure1) self.canvas2 = figureCanvas(figure2) self.canvas1.draw() self.canvas2.draw() layout = QHBoxLayout(self) layout.addWidget(self.canvas1) layout.addWidget(self.canvas2)
def draw_pic(self, radii, result): if (self.canvas is not None): self.layout.removeWidget(self.canvas) figure = plt.gcf() #返回当前的figure self.canvas = figureCanvas(figure) radii = [abs(1.0 / i * 20) for i in list(radii)] ax = axes([0.025, 0.025, 0.95, 0.95], polar=True) #axes(轴)代表维度,polar用来画极坐标图 N = 10 #元素的个数 theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) # 是一个pi/10的递增的列表#print "theta=%s"%theta width = np.pi / 4 * np.random.rand(N) #小于4分之1 PI的随机数 bars = plt.bar(theta, radii, width=width, bottom=0.0) i = 0 for r, bar in zip(radii, bars): bar.set_facecolor(cm.jet(r / 1000.)) bar.set_alpha(0.5) height = bar.get_height() ax.text(bar.get_x() + bar.get_width() / 2., 1.03 * height, "%s" % result[i]) i += 1 ax.set_xticklabels(["Funcitons"]) ax.set_yticklabels(["possiblitly" ]) # savefig('figure/polar_ex_LSI.png', dpi=48) self.canvas.draw() self.layout.addWidget(self.canvas)
def __init__(self, parent=None): super(Example3, self).__init__(parent) figure = plt.figure(figsize=(10, 60), facecolor='green', edgecolor='red') # figsize = (8,4)表示figure的大小,屏幕显示 640 * 320 , 输出显示 800*400,这个要注意。 # 显示色和外框线条颜色设置。 self.canvas = figureCanvas(figure) plt.subplot(211) # 子区,2行,2列 x = [1, 2, 3] y = [4, 5, 6] plt.plot(x, y) plt.title('Example') plt.xlabel('x') plt.ylabel('y') plt.subplot(223) # 子区,2行,2列 x = [1, 2, 3] y = [4, 5, 6] plt.bar(x, y) plt.title('Example') plt.xlabel('x') plt.ylabel('y') plt.subplot(224) # 子区,2行,2列 x = [1, 2, 3] y = [4, 5, 6] plt.scatter(x, y) plt.title('Example') plt.xlabel('x') plt.ylabel('y') self.canvas.draw() layout = QHBoxLayout(self) layout.addWidget(self.canvas)
def __init__(self, parent): # super(StocksGraphView, self).__init__(parent) self.fatherHandle = parent self.figure = plt.gcf() self.ax = self.figure.gca() self.canvas = figureCanvas(self.figure) self.hintText = self.ax.text(-.5, -.5, "", ha="right", va="baseline", fontdict={"size": 15}) self.figure.canvas.mpl_connect('key_press_event', self._on_key_press) self.figure.canvas.mpl_connect('button_press_event', self._on_button_press) # figure.canvas.mpl_disconnect(figure.canvas.manager.key_press_handler_id) self.figure.canvas.mpl_connect('motion_notify_event', self._on_mouse_move) self._lines = {} self._hHintLine = None self._vHintLine = None self.ax.fmt_date = matplotlib.dates.DateFormatter('%Y-%m-%d') self.strpdate2num = matplotlib.dates.strpdate2num('%Y-%m-%d') plt.subplots_adjust(left=.04, bottom=.0, right=.98, top=.97, wspace=.0, hspace=.0) plt.minorticks_on() self.ax.grid() self.ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%y\n-\n%m\n-\n%d'))
def createSubOverviewPage(self): layout = QtGui.QGridLayout() w = QtGui.QWidget() sns.set(style="whitegrid") f, ax = plt.subplots(figsize=(20, 12)) canvas = figureCanvas(f) canvas.setParent(w) sns.set(style="whitegrid") q = QtSql.QSqlQuery("""SELECT EXP_DATE, SUM(AMOUNT), SUM(AMOUNT*(1+EXP_RETURN*(datediff(EXP_DATE, SETTLE_DATE)+1)/36500.0)) FROM LIABILITY WHERE EXP_DATE>='%s' GROUP BY EXP_DATE ORDER BY EXP_DATE"""%self.sysdate.date().toPyDate()) dates, vals = [], [] x_amt = range(0,1000000000,100000000) while q.next(): dates.append(q.value(0).toDate().toPyDate().isoformat()) vals.append((q.value(1).toDouble()[0], q.value(2).toDouble()[0])) data = pd.DataFrame(vals, index=dates, columns=['Amount', 'Total Return']) # Plot the total crashes sns.set_color_codes("pastel") sns.barplot(x='Total Return', y=dates, data=data, label='Interest', color="b") # Plot the crashes where alcohol was involved sns.set_color_codes("muted") sns.barplot(x='Amount', y=dates, data=data, label="Principal", color="b") # Add a legend and informative axis label ax.legend(ncol=2, loc="upper right", frameon=True) ax.set(ylabel="Maturity Date", title='Liability Overview') sns.despine(left=True, bottom=True) layout.addWidget(w, 0, 0, 1, 1) return layout
def __init__(self, parent=None, tp=1, trade_interval=60): super(figure, self).__init__(parent) self.type = tp figure.fig_num += 1 self.fig_num = figure.fig_num self.title = '' self.sid = '' self.init_figure() self.interval = del2num(trade_interval) self.canvas1 = figureCanvas(self.figure1) self.canvas1.draw() self.layout = QHBoxLayout(self) self.layout.addWidget(self.canvas1) if self.type != figure.CDF_PLOT: if trade_interval < 60: self.xlocater = SecondLocator(bysecond=range(0, 60, trade_interval)) self.xformatter = DateFormatter("%H:%M:%S") else: self.xlocater = MinuteLocator(byminute=range(0, 60, trade_interval / 60)) self.xformatter = DateFormatter("%H:%M") else: if trade_interval < 5: self.xlocater = SecondLocator(bysecond=range(0, 60, 12 * trade_interval)) self.xformatter = DateFormatter("%H:%M:%S") else: self.xlocater = MinuteLocator(byminute=range(0, 60, trade_interval / 5)) self.xformatter = DateFormatter("%H:%M")
def __init__(self,parent=None,year=0,month=0,day=0,stock='0'): super(cdf_graph,self).__init__(parent) interval=5 self.data=getHistoricalData(year=year,month=month,day=day,stock=stock,interval=interval) interval=delta2num(interval) figure2 = plt.figure(2) x3 = [ele[0] for ele in self.data] y3 = getOrderSize(stock) for i in range(1,len(y3)): y3[i]=y3[i]+y3[i-1] y3=[ele/y3[-1] for ele in y3] ax3=figure2.add_subplot(111) ax3.xaxis.set_major_locator(minutes) ax3.xaxis.set_major_formatter(minute_formatter) line_percent=ax3.plot(x3,y3,'-D',label='Completion Percentage') figure2.autofmt_xdate() plt.grid() plt.legend(loc='upper left') plt.title('%s'%stock.upper(),fontsize=20) plt.xlabel('Time',fontsize=20) plt.ylabel('Completion Percentage',fontsize=15) self.canvas2 = figureCanvas(figure2) self.canvas2.draw() self.toolbar2=NavigationToolBar(self.canvas2,self) layout = QHBoxLayout(self) rightLayout=QVBoxLayout(self) layout.addLayout(rightLayout) rightLayout.addWidget(self.canvas2) rightLayout.addWidget(self.toolbar2)
def __init__(self,parent=None): super(DrawWidget,self).__init__(parent) figure = plt.gcf() #返回当前的figure self.canvas = figureCanvas(figure) x = [1,2,3] y = [4,5,6] plt.plot(x,y) plt.title('Example') plt.xlabel('x') plt.ylabel('y') self.canvas.draw() layout = QHBoxLayout(self) layout.addWidget(self.canvas)
def __init__(self,parent=None): super(Example1,self).__init__(parent) # 返回当前的figure figure = plt.gcf() self.canvas = figureCanvas(figure) x = [1,2,3] y = [4,5,6] plt.plot(x,y) plt.title('Example') plt.xlabel('x') plt.ylabel('y') self.canvas.draw() layout = QHBoxLayout(self) layout.addWidget(self.canvas)
def __init__(self, parent=None): super(Example4, self).__init__(parent) figure = plt.figure(figsize=(10, 6), dpi=100, facecolor='white') canvas = figureCanvas(figure) x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c = np.cos(x) s = np.sin(x) plt.plot(x, c, color='blue', linewidth=1.0, linestyle='-', label='$cos(x)$') # 设置颜色,线条的格式和粗细 plt.plot(x, s, color='green', linewidth=1.0, linestyle='-', label='$sin(x)$') ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) plt.xlim(x.min() * 1.1, x.max() * 1.1) # X轴的范围 plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$']) # X轴的刻度值 plt.ylim(s.min() * 1.1, s.max() * 1.1) # Y轴的范围 plt.yticks([-1, 0, 1], [r'$-1$', r'$0$', r'$+1$']) # 设置Y轴的刻度值,第二个参数对其进行格式化 # 添加注释和箭头以及虚线 t = np.pi * 2 / 3 plt.plot([t, t], [0, np.sin(t)], color='red', linewidth=2.5, linestyle='--') plt.scatter([t], [np.sin(t)], 50, color='red') # 50代表散点的大小,应该是像素值 plt.plot([t, t], [0, np.cos(t)], color='green', linewidth=2.5, linestyle='--') plt.scatter([t], [np.cos(t)], 50, color='green') plt.annotate(r'$sin(\frac{2\pi}{3})=(\frac{\sqrt{3}}{2})$', xy=(t, np.sin(t)), xycoords='data', xytext=(10, 30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.1')) plt.annotate(r'$cos(\frac{2\pi}{3})=(\frac{\sqrt{3}}{2})$', xy=(t, np.cos(t)), xycoords='data', xytext=(-120, -30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.1')) # 后面的参数应该是角度,类似于偏离度,1的时候接近垂直 plt.legend(loc='upper left') for i in ax.get_xticklabels() + ax.get_yticklabels(): i.set_fontsize(15) i.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.65)) canvas.draw() layout = QHBoxLayout(self) layout.addWidget(canvas)
def __init__(self, parent=None): super(DrawWidget3, self).__init__(parent) figure = plt.figure(figsize=(10, 6), dpi=100, facecolor='white') canvas = figureCanvas(figure) plt.axes([0.1, 0.1, 0.5, 0.5]) plt.xticks([]) plt.yticks([]) plt.text(0.2, 0.2, 'hello axes', alpha='0.65', size=16) plt.text(0.6, 0.4, 'hello axes', alpha='0.65', size=16) canvas.draw() layout = QHBoxLayout(self) layout.addWidget(canvas)
def createSubOverviewPage(self): layout = QtGui.QGridLayout() w = QtGui.QWidget() sns.set(style="whitegrid") f, ax = plt.subplots(figsize=(20, 12)) canvas = figureCanvas(f) canvas.setParent(w) sns.set(style="whitegrid") q = QtSql.QSqlQuery( """SELECT EXP_DATE, SUM(AMOUNT), SUM(AMOUNT*(1+EXP_RETURN*(datediff(EXP_DATE, SETTLE_DATE)+1)/36500.0)) FROM LIABILITY WHERE EXP_DATE>='%s' GROUP BY EXP_DATE ORDER BY EXP_DATE""" % self.sysdate.date().toPyDate()) dates, vals = [], [] x_amt = range(0, 1000000000, 100000000) while q.next(): dates.append(q.value(0).toDate().toPyDate().isoformat()) vals.append((q.value(1).toDouble()[0], q.value(2).toDouble()[0])) data = pd.DataFrame(vals, index=dates, columns=['Amount', 'Total Return']) # Plot the total crashes sns.set_color_codes("pastel") sns.barplot(x='Total Return', y=dates, data=data, label='Interest', color="b") # Plot the crashes where alcohol was involved sns.set_color_codes("muted") sns.barplot(x='Amount', y=dates, data=data, label="Principal", color="b") # Add a legend and informative axis label ax.legend(ncol=2, loc="upper right", frameon=True) ax.set(ylabel="Maturity Date", title='Liability Overview') sns.despine(left=True, bottom=True) layout.addWidget(w, 0, 0, 1, 1) return layout
def __init__(self, parent): # super(StocksGraphView, self).__init__(parent) self.fatherHandle = parent self.figure = plt.gcf() self.ax = self.figure.gca() self.canvas = figureCanvas(self.figure) self.hintText = self.ax.text(-.5, -.5, "", ha="right", va="baseline", fontdict={"size": 15}) self.figure.canvas.mpl_connect('key_press_event', self._on_key_press) self.figure.canvas.mpl_connect('button_press_event', self._on_button_press) # figure.canvas.mpl_disconnect(figure.canvas.manager.key_press_handler_id) self.figure.canvas.mpl_connect('motion_notify_event', self._on_mouse_move) self._lines = {} self._hHintLine = None self._vHintLine = None self.ax.fmt_date = matplotlib.dates.DateFormatter('%Y-%m-%d') self.strpdate2num = matplotlib.dates.strpdate2num('%Y-%m-%d') plt.subplots_adjust(left=.04, bottom=.0, right=.98, top=.97, wspace=.0, hspace=.0) plt.minorticks_on() self.ax.grid() self.ax.xaxis.set_major_formatter( matplotlib.dates.DateFormatter('%y\n-\n%m\n-\n%d'))
def __init__(self, parent=None): super(DrawWidget, self).__init__(parent) figure = plt.gcf() x = [1, 2, 3, 3] y = [4, 5, 5, 6] t = np.arange(0., 5., 0.2) # plt.plot(t, t, 'g--', t, t*2, 'bs', t, t**2, 'r^') # plt.axis([-2, 10, -2, 30]) # # 是指定xy坐标的起始范围,它的参数是列表[xmin, xmax, ymin, ymax]。 # plt.text(2, .25, r'$\mu=100,\ \sigma=15$') # plt.title('example') # plt.xlabel('x') # plt.ylabel('y') self.xxlineH = None self.xxlineV = None self.xxax = figure.gca() # fig, ax = plt.subplots(1) # np.random.seed(14) x = ppl.plot(figure.gca(), t, t, '--', color=(255/255.,150/255.,250/255.), label=str('t, t'), pickradius=28.0) ppl.plot(figure.gca(), t, t*2, label=str(' t, t*2'), pickradius=8.0) ppl.plot(figure.gca(), t, t**2, label=str('t, t**2'), pickradius=8.0) ppl.legend(figure.gca(), loc='upper left', ncol=3) # figure.gca().lines.remove(x[0]) # ax = plt.gca()#移动坐标轴 # ax.spines['right'].set_color('none')#去除右边的轴 # ax.spines['top'].set_color('none')#去除顶轴 # ax.xaxis.set_ticks_position('bottom') # #下轴移至数据0点,理想状态下0点为中心点,具体跟数据位置有关 # ax.spines['bottom'].set_position(('data', 0)) # ax.yaxis.set_ticks_position('left') # ax.spines['left'].set_position(('data', 0)) # plt.xlim(t.min()*1.1, t.max()*1.1)#X轴的范围 # plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],#从新定义刻度 # [r'$-\pi$',r'$-\pi/2$',r'$0$',r'$\pi/2$',r'$\pi$'])#X轴的刻度值 # plt.ylim(s.min()*1.1,s.max()*1.1)#Y轴的范围 # plt.yticks([-1,0,1],[r'$-1$',r'$0$',r'$+1$']) #设置Y轴的刻度值,第二个参数对其进行格式化 plt.annotate(r'$sin(\frac{2\pi}{3})=(\frac{\sqrt{3}}{2})$', xy=(5, 5), xycoords='data', xytext=(15, 200), textcoords='offset points', fontsize=16, arrowprops = dict(arrowstyle='->', connectionstyle='arc3,rad=.1')) plt.plot([5, 5], [0, 5], 'ro', color='black', linewidth=1.0, linestyle='--', label='$cos(x)$') # plt.plot([5, 5], [0, 5],'ro', linewidth=5.0, label='$sin(x)$') # plt.scatter([5, 5], [0, 5], 50, color='red') # for i in ax.get_xticklabels() + ax.get_yticklabels():#从新设置所有bbox # i.set_fontsize(15) # i.set_bbox(dict(facecolor='white',edgecolor='none',alpha=0.65)) # 'button_press_event':鼠标按键按下时触发 # 'button_release_event':鼠标按键释放时触发 # 'motion_notify_event':鼠标移动时触发 # 当前的所有注册的响应函数可以通过Figure.canvas.callbacks.callbacks for key, funcs in figure.canvas.callbacks.callbacks.iteritems(): print key for cid, wrap in sorted(funcs.items()): func = wrap.func print " {0}:{1}.{2}".format(cid, func.__module__, func) self.text = figure.gca().text(0.5, 10.5, "event", ha="center", va="center", fontdict={"size":20}) self.canvas = figureCanvas(figure) self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus) ##qt4需要加这两句,否者信号被qt拦截,无法到达matplot self.canvas.setFocus() figure.canvas.mpl_connect('key_press_event', self.on_key_press) # figure.canvas.mpl_disconnect(figure.canvas.manager.key_press_handler_id) figure.canvas.mpl_connect('motion_notify_event', self.on_mouse_move) self.canvas.draw() figure2 = plt.figure(2, figsize=(8, 4), facecolor='green', edgecolor='red') #figsize = (8,4)表示figure的大小,屏幕显示 640 * 320 , 输出显示 800*400,这个要注意。 #显示色和外框线条颜色设置。 self.canvas2 = figureCanvas(figure2) plt.subplot(311)# 子区,3行,1列, 第1个 y = [1, 2, 3, 4] x = [4, 5, 5, 6] plt.plot(x, y, 'bo', x, y, 'r') plt.title('examrple2') plt.xlabel('x') plt.ylabel('y') plt.subplot(323)# 子区,3行,2列, 第3个 x = [1, 2, 3] y = [4, 5, 6] plt.bar(x, y) plt.title('Example3') plt.xlabel('x') plt.ylabel('y') plt.subplot(336)# 子区,3行,3列, 第6个 x = [1, 2, 3] y = [4, 5, 6] plt.scatter(x, y) plt.title('Example4') plt.xlabel('x') plt.ylabel('y') plt.subplot(313)# 子区,3行,1列, 第3个 mu, sigma = 100, 15 x = mu + sigma*np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 150, normed=1, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60, .025, r'$\mu=100,\ \sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) # import prettyplotlib as ppl # fig, ax = plt.subplots(1) # np.random.seed(14) # n = 10 # ppl.bar(plt.gca(), np.arange(n), np.abs(np.random.randn(n)), annotate=True, grid='y') layout = QtGui.QHBoxLayout(self) layout.addWidget(self.canvas) layout.addWidget(self.canvas2) self.canvas2.draw()
""" 实验数据x, y和拟合函数之间的差,p为拟合需要找到的系数 """ return y - func(x, p) x = np.linspace(0, -2*np.pi, 100) A, k, theta = 10, 0.34, np.pi/6 # 真实数据的函数参数 y0 = func(x, [A, k, theta]) # 真实数据 y1 = y0 + 2 * np.random.randn(len(x)) # 加入噪声之后的实验数据 p0 = [7, 0.2, 0] # 第一次猜测的函数拟合参数 # 调用leastsq进行数据拟合 # residuals为计算误差的函数 # p0为拟合参数的初始值 # args为需要拟合的实验数据 plsq = leastsq(residuals, p0, args=(y1, x)) print u"真实参数:", [A, k, theta] print u"拟合参数", plsq[0] # 实验数据拟合后的参数 figure = plt.gcf() figureCanvas(figure) plt.plot(x, y0, label=u"真实数据") plt.plot(x, y1, label=u"带噪声的实验数据") plt.plot(x, func(x, plsq[0]), label=u"拟合数据") plt.legend() plt.show() from scipy.stats import pearsonr
def __init__(self, parent=None, stock='sz002024', year=0, month=0, day=0): super(graph, self).__init__(parent) interval = 5 self.data = getHistoricalData(stock, year, month, day, interval=interval) interval = delta2num(interval) figure1 = plt.figure(1) #返回当前的figure x = [ele[0] for ele in self.data] y = [ele[1] for ele in self.data] tm = datetime(year, month, day, 11, 30, 0) ta = datetime(year, month, day, 13, 0, 0) morningend = date2num(tm) afternoonbegin = date2num(ta) c = 0 x01 = [] x02 = [] y01 = [] y02 = [] for ele in x: if ele <= morningend: x01.append(ele) y01.append(y[c]) elif ele >= afternoonbegin: x02.append(ele) y02.append(y[c]) c = c + 1 ymax = max(y) ymin = min(y) x1 = [ele + interval * 0.1 for ele in x] y1 = [ele[3] for ele in self.data] s = sum(y1) y1 = [ele / s * 100 for ele in y1] y1max = max(y1) x2 = [ele + interval * 0.5 for ele in x] print(len(x2)) y2 = getOrderSize(stock) y2 = [ele * 100 for ele in y2] y1max = max(y1max, max(y2)) #ratio=0.3 #y2 = [ele*sum(y1)*ratio for ele in y2] ax1 = figure1.add_subplot(111) ax1.xaxis.set_major_locator(minutes) ax1.xaxis.set_major_formatter(minute_formatter) plt.ylabel('Volume(%)', fontsize=15) plt.ylim([0, y1max * 1.5]) plt.xlabel('Time', fontsize=15) ax2 = ax1.twinx() bar_history = ax1.bar(x1, y1, width=interval * 0.4, color='c', label='Historical Volume') bar_order = ax1.bar(x2, y2, width=interval * 0.4, color=[1, 0.4, 0.6], label='Order Size') line_price, = ax2.plot(x01, y01, color='b', label='Price') ax2.plot(x02, y02, color='b') plt.title('%s' % stock.upper(), fontsize=20) plt.ylabel('Price', fontsize=15) plt.ylim([ymin - 2 * (ymax - ymin), ymax + 0.25 * (ymax - ymin)]) figure1.autofmt_xdate() plt.grid() plt.legend(handles=(line_price, bar_history, bar_order), loc='upper right', ncol=3) #plt.legend(handles=(bar_history,),bbox_to_anchor=(0.5,-0.25),loc='lower center') plt.tight_layout() #plt.autoscale(tight=True) self.canvas1 = figureCanvas(figure1) self.canvas1.draw() self.toolbar1 = NavigationToolBar(self.canvas1, self) layout = QHBoxLayout(self) leftLayout = QVBoxLayout(self) rightLayout = QVBoxLayout(self) layout.addLayout(leftLayout) #layout.addLayout(rightLayout) leftLayout.addWidget(self.canvas1) leftLayout.addWidget(self.toolbar1)
实验数据x, y和拟合函数之间的差,p为拟合需要找到的系数 """ return y - func(x, p) x = np.linspace(0, -2 * np.pi, 100) A, k, theta = 10, 0.34, np.pi / 6 # 真实数据的函数参数 y0 = func(x, [A, k, theta]) # 真实数据 y1 = y0 + 2 * np.random.randn(len(x)) # 加入噪声之后的实验数据 p0 = [7, 0.2, 0] # 第一次猜测的函数拟合参数 # 调用leastsq进行数据拟合 # residuals为计算误差的函数 # p0为拟合参数的初始值 # args为需要拟合的实验数据 plsq = leastsq(residuals, p0, args=(y1, x)) print u"真实参数:", [A, k, theta] print u"拟合参数", plsq[0] # 实验数据拟合后的参数 figure = plt.gcf() figureCanvas(figure) plt.plot(x, y0, label=u"真实数据") plt.plot(x, y1, label=u"带噪声的实验数据") plt.plot(x, func(x, plsq[0]), label=u"拟合数据") plt.legend() plt.show() from scipy.stats import pearsonr
def __init__(self,parent=None,stock='0',year=0,month=0,day=0,alg='TVWAP'): super(graph,self).__init__(parent) interval=5 self.data=getHistoricalData(stock,year,month,day,interval=interval) interval=delta2num(interval) figure1 = plt.figure(1) #返回当前的figure x = [ele[0] for ele in self.data] y = [ele[1] for ele in self.data] tm=datetime(year,month,day,11,30,0) ta=datetime(year,month,day,13,0,0) morningend=date2num(tm) afternoonbegin=date2num(ta) c=0; x01=[];x02=[]; y01=[];y02=[]; for ele in x: if ele<=morningend: x01.append(ele) y01.append(y[c]) elif ele>=afternoonbegin: x02.append(ele) y02.append(y[c]) c=c+1 if alg=='TVWAP': ymax=max(y);ymin=min(y) x1 = [ele+interval*0.1 for ele in x] y1 = [ele[2] for ele in self.data] s=sum(y1) y1max=max(y1) x2 = [ele+interval*0.5 for ele in x] print(len(x2)) y2 = getOrderSize(stock) y2 = [ele*s/10 for ele in y2] y1max=max(y1max,max(y2)) elif alg=='VWAP': ymax=max(y);ymin=min(y) x1 = [ele+interval*0.1 for ele in x] y1 = [ele[2] for ele in self.data] s=sum(y1) y1max=max(y1) x2 = [ele+interval*0.5 for ele in x] print(len(x2)) y2 = self.__getOrderSize() elif alg=='TWAP': ymax=max(y);ymin=min(y) x1 = [ele+interval*0.1 for ele in x] y1 = [ele[2] for ele in self.data] s=sum(y1) y1=[ele for ele in y1] y1max=max(y1) x2 = [ele+interval*0.5 for ele in x] print(len(x2)) y2 = [] for ele in range(len(y1)): y2.append(s/len(y1)/5) #ratio=0.3 #y2 = [ele*sum(y1)*ratio for ele in y2] ax1=figure1.add_subplot(111) # ax1.xaxis.set_major_locator(minutes) # ax1.xaxis.set_major_formatter(minute_formatter) plt.ylabel('Volume',fontsize=15) plt.ylim([0,y1max*1.5]) plt.xlabel('Time',fontsize=15) ax2=ax1.twinx() # if alg=='TVWAP': # bar_history=ax1.bar(x1,y1,width=interval*0.4,color='c',label='Historical Volume') # else: # bar_history=ax1.bar(x1,y1,width=interval*0.4,color='c',label='Volume') # bar_order=ax1.bar(x2,y2,width=interval*0.4,color=[1,0.4,0.6],label='Order Size') x01=[736321.3958912037, 736321.3959606482, 736321.3959953703, 736321.3961342593, 736321.3962037037, 736321.3962731481, 736321.3964120371, 736321.3964814815, 736321.3965509259, 736321.3965856482, 736321.3966898149, 736321.3967592593, 736321.3969328704, 736321.3971759259, 736321.3973842593, 736321.3974537037, 736321.397488426, 736321.3975578704, 736321.397662037, 736321.3977314815, 736321.3977662037, 736321.3979398148, 736321.3993634259, 736321.399675926, 736321.3997106481, 736321.3998148148, 736321.3999189815, 736321.3999884259, 736321.4000578703, 736321.4000925926, 736321.4002662037, 736321.4003703704, 736321.4005439815, 736321.4006134259, 736321.400787037, 736321.4008217592, 736321.4008912037, 736321.4010300926, 736321.4011689815, 736321.4012731481, 736321.4013078704, 736321.4013773148, 736321.4014814815, 736321.4015162037, 736321.4015509259, 736321.4015856482, 736321.401863426, 736321.4019675925, 736321.4027893519, 736321.402962963, 736321.4031018518, 736321.4031712963, 736321.4032407408, 736321.4033101852, 736321.4033796296, 736321.403587963, 736321.4036226852, 736321.4036921297, 736321.4037615741, 736321.4040046296, 736321.404212963, 736321.4044212963, 736321.4044560185, 736321.4044907407, 736321.404525463, 736321.4046990741, 736321.4047337963, 736321.4065162037, 736321.406724537, 736321.4068981481, 736321.4069328704, 736321.4069675925, 736321.4070023148, 736321.4070370371, 736321.4071412038, 736321.4098148148, 736321.4099189815, 736321.4099537038, 736321.4099884259, 736321.4134953704, 736321.413599537, 736321.4136689815, 736321.4141203704, 736321.4142245371, 736321.4142939815, 736321.4143287037, 736321.4143981482, 736321.4145717593, 736321.414675926, 736321.4147453704, 736321.4150578703, 736321.4152546297, 736321.415300926, 736321.4153587963, 736321.4155671296, 736321.415636574, 736321.4157060186, 736321.4160185185, 736321.4160879629, 736321.4168171296, 736321.4168865741, 736321.417199074, 736321.4176851852, 736321.4177893519, 736321.4178587963, 736321.4182060185, 736321.4182407408, 736321.4185532407, 736321.4168171296, 736321.4168865741, 736321.417199074, 736321.4176851852, 736321.4177893519, 736321.4178587963, 736321.4182060185, 736321.4182407408, 736321.4185532407, 736321.4187268518, 736321.4187962963, 736321.4189699074, 736321.4190509259, 736321.4190856481, 736321.4191898148, 736321.4192939815, 736321.4193634259, 736321.4193981482, 736321.4194328703, 736321.419537037, 736321.4195717593, 736321.4196412037, 736321.4197106481, 736321.4198842592, 736321.4199189815] y01=[0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009, 0.01, 0.011, 0.012, 0.013, 0.014, 0.015, 0.016, 0.017, 0.018, 0.019, 0.02, 0.021, 0.0215, 0.023, 0.0245, 0.026, 0.0275, 0.029, 0.0305, 0.032, 0.0335, 0.035, 0.0365, 0.038, 0.0395, 0.041, 0.0425, 0.044, 0.0455, 0.047, 0.0485, 0.05, 0.0515, 0.053, 0.0545, 0.056, 0.0575, 0.059, 0.06, 0.0605, 0.061, 0.0615, 0.062, 0.0625, 0.063, 0.0635, 0.064, 0.0645, 0.065, 0.0655, 0.066, 0.0665, 0.067, 0.0675, 0.068, 0.0685, 0.069, 0.0695, 0.07, 0.0705, 0.071, 0.0715, 0.072, 0.0725, 0.073, 0.0735, 0.074, 0.0745, 0.075, 0.0755, 0.0775, 0.0795, 0.0815, 0.0835, 0.0855, 0.0875, 0.0895, 0.0915, 0.0935, 0.0955, 0.0975, 0.0995, 0.1015, 0.1035, 0.1055, 0.1075, 0.1095, 0.1115, 0.1135, 0.1155, 0.1175, 0.1195, 0.1215, 0.1235, 0.1255, 0.1275, 0.1295, 0.1315, 0.1325, 0.135, 0.1375, 0.14, 0.1425, 0.145, 0.1475, 0.15, 0.1525, 0.155, 0.1575, 0.16, 0.1625, 0.165, 0.1675, 0.17, 0.1725, 0.175, 0.1775, 0.18, 0.1825, 0.185, 0.1875, 0.19, 0.1925, 0.195] line_price,=ax2.plot(x01,y01,color='b',label='Price') # ax2.plot(x02,y02,color='b') plt.title('%s'%stock.upper(),fontsize=20) plt.ylabel('Price',fontsize=15) plt.ylim([ymin-2*(ymax-ymin),ymax+0.25*(ymax-ymin)]) # figure1.autofmt_xdate() plt.grid() # plt.legend(handles=(line_price,bar_history,bar_order),loc='upper right',ncol=3) #plt.legend(handles=(bar_history,),bbox_to_anchor=(0.5,-0.25),loc='lower center') plt.tight_layout() plt.autoscale(tight=True) self.canvas1 = figureCanvas(figure1) self.canvas1.draw() self.toolbar1=NavigationToolBar(self.canvas1,self) layout = QHBoxLayout(self) leftLayout=QVBoxLayout(self) rightLayout=QVBoxLayout(self) layout.addLayout(leftLayout) #layout.addLayout(rightLayout) leftLayout.addWidget(self.canvas1) leftLayout.addWidget(self.toolbar1)
def __init__(self, parent=None): super(DrawWidget2, self).__init__(parent) figure = plt.figure(figsize=(10, 6), dpi=100, facecolor='white') canvas = figureCanvas(figure) x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c = np.cos(x) s = np.sin(x) plt.plot(x, c, color='blue', linewidth=1.0, linestyle='-', label='$cos(x)$') # 设置颜色,线条的格式和粗细 plt.plot(x, s, color='green', linewidth=1.0, linestyle='-', label='$sin(x)$') ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) plt.xlim(x.min() * 1.1, x.max() * 1.1) # X轴的范围 plt.xticks( [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$']) # X轴的刻度值 plt.ylim(s.min() * 1.1, s.max() * 1.1) # Y轴的范围 plt.yticks([-1, 0, 1], [r'$-1$', r'$0$', r'$+1$']) # 设置Y轴的刻度值,第二个参数对其进行格式化 # 添加注释和箭头以及虚线 t = np.pi * 2 / 3 plt.plot([t, t], [0, np.sin(t)], color='red', linewidth=2.5, linestyle='--') plt.scatter([t], [np.sin(t)], 50, color='red') # 50代表散点的大小,应该是像素值 plt.plot([t, t], [0, np.cos(t)], color='green', linewidth=2.5, linestyle='--') plt.scatter([t], [np.cos(t)], 50, color='green') plt.annotate(r'$sin(\frac{2\pi}{3})=(\frac{\sqrt{3}}{2})$', xy=(t, np.sin(t)), xycoords='data', xytext=(10, 30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.1')) plt.annotate( r'$cos(\frac{2\pi}{3})=(\frac{\sqrt{3}}{2})$', xy=(t, np.cos(t)), xycoords='data', xytext=(-120, -30), textcoords='offset points', fontsize=16, arrowprops=dict( arrowstyle='->', connectionstyle='arc3,rad=.1')) # 后面的参数应该是角度,类似于偏离度,1的时候接近垂直 plt.legend(loc='upper left') for i in ax.get_xticklabels() + ax.get_yticklabels(): i.set_fontsize(15) i.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.65)) canvas.draw() layout = QHBoxLayout(self) layout.addWidget(canvas)