def lab_4_get_graphics(student_data, source_data): graphics = [] N0 = len(student_data["student_signal"]) d = student_data["student_signal"] # сигнал, вводимый студентом b = np.array([float(student_data["student_b"])]) a = student_data["student_filter"] # фильтр, вводимый студентом fig, ax = plt.subplots(figsize=(6, 6)) z = signal.lfilter(b, a, d) ax.plot(np.arange(N0), z, 'y', linewidth=2.0) ax.plot(np.arange(N0), np.ones((N0, 1)) * (0.05 * max(z)), 'r') ax.plot(np.arange(N0), np.ones((N0, 1)) * (-0.05 * max(z)), 'r') html = mpld3.fig_to_d3(fig) graphics.append( { "id": "graphic_1", "html": html } ) fig, ax = plt.subplots(figsize=(6, 6)) fz = np.abs(np.fft.fft(z)) plt.plot(np.arange(N0), fz, 'y', linewidth=2.0) plt.plot(np.arange(N0), np.ones((N0, 1)) * (0.707 * max(fz)), 'r') html = mpld3.fig_to_d3(fig) graphics.append( { "id": "graphic_2", "html": html } ) return graphics
def lab_1_get_graphics(student_data, source_data): graphics = [] N0 = len(student_data["student_signal"]) d = student_data["student_signal"] # сигнал, вводимый студентом b = student_data["student_filter"] # фильтр, вводимый студентом a = float(student_data["student_a"]) if source_data["filter_type"]["window"]["name"] == "hamming": w = np.hamming(len(b)) z = signal.lfilter(b * w, 1, d) fz = np.abs(np.fft.fft(z)) elif source_data["filter_type"]["window"]["name"] == "blackman": w = np.blackman(len(b)) z = signal.lfilter(b * w, a, d) # тут написать алгоритм для Блэкмана fz = np.abs(np.fft.fft(z)) else: # прямоугольное окно z = signal.lfilter(b, a, d) fz = np.abs(np.fft.fft(z)) fig, ax = plt.subplots(figsize=(6, 6)) ax.stem(np.arange(N0), z, 'c') ax.plot(np.arange(N0), z, 'y', linewidth=3.0) ax.plot(np.arange(N0), np.ones((N0, 1)) * (0.707 * max(z)), 'r', linewidth=3.0) # w = np.hamming(Ns) # z = signal.lfilter(b*w, a, d) # ax.stem(np.arange(N0), z) # ax.plot(np.arange(N0), np.ones((N0, 1)) * (0.707 * max(z)), 'r') html = mpld3.fig_to_d3(fig) graphics.append( { "id": "graphic_1", "html": html } ) fig, ax = plt.subplots(figsize=(6, 6)) # if source_data["filter_type"]["window"]["name"] == "hamming": # ax.semilogy(fz) # else: ax.plot(np.arange(N0), fz, 'c', linewidth=3.0) ax.plot(np.arange(N0), np.ones((N0, 1)) * (0.707 * max(fz)), 'r', linewidth=3.0) html = mpld3.fig_to_d3(fig) graphics.append( { "id": "graphic_2", "html": html } ) return graphics
def lab_5_get_graphic_1(student_data, source_data): graphics = [] s = student_data["student_s"] s1 = student_data["student_s1"] fig, ax = plt.subplots(figsize=(6, 6)) ax.stem(abs(np.fft.fft(s))) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_1", "html": html}) fig, ax = plt.subplots(figsize=(6, 6)) ax.stem(abs(np.fft.fft(s1))) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_2", "html": html}) return graphics
def lab_7_get_graphic_2(student_data): student_sm = student_data["student_Sm"] fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(student_sm, linewidth=2.0) html = mpld3.fig_to_d3(fig) graphic = {"id": "graphic_2", "html": html} return graphic
def combine_testplots(wildcard='test_plots/*.py', outfile='test_plots.html', d3_url=None): """Generate figures from the plots and save to an HTML file Parameters ---------- wildcard : string a regex matching files outfile : string the output HTML file for saving the results d3_url : string the URL of the d3 library to use. If not specified, a standard web address will be used. """ fig_html = [] for filename in glob.glob('test_plots/*.py'): dirname, fname = os.path.split(filename) modulename = os.path.splitext(fname)[0] if dirname not in sys.path: sys.path.append(dirname) f = __import__(modulename) if hasattr(f, 'main'): print "running {0}".format(filename) fig = f.main() fig_html.append(fig_to_d3(fig, d3_url)) print "writing results to {0}".format(outfile) template = '<html>\n{content}\n</html>' with open(outfile, 'w') as f: f.write('<html>\n\n') for fig in fig_html: f.write(fig) f.write('\n\n</html>')
def lab_2_get_graphics_2(source_data, correct_answer): graphics = [] K = float(correct_answer["K_2"]) N3 = int(source_data["N3"]) fig, ax = plt.subplots(figsize=(6, 6)) d3 = [np.exp(2j * math.pi * K * x / N3) for x in np.arange(N3)] ax.plot(np.arange(N3), np.real(d3), 'y', linewidth=2.0) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_3", "html": html}) fig, ax = plt.subplots(figsize=(6, 6)) sp = np.abs(np.fft.fft(d3)) ax.stem(np.arange(N3), sp, 'c') html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_4", "html": html}) return graphics
def lab_7_get_graphic_3(source_data, correct_answer): graphics = [] N1 = int(correct_answer["N1"]) S1p = correct_answer["S1p"] SD = correct_answer["SD"] fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(np.arange(0, N1 * 8), S1p[0:np.int(N1 * 8)]) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_3_1", "html": html}) fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(np.arange(0, N1 * 8), SD[0:np.int(N1 * 8)]) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_3_2", "html": html}) return graphics
def lab_2_get_graphics_1(source_data, correct_answer): graphics = [] K = int(correct_answer["K_1"]) N3 = int(source_data["N3"]) fig, ax = plt.subplots(figsize=(6, 6)) # d3 = [math.cos((math.pi * x) / 2) for x in np.arange(N3)] d3 = [math.cos((math.pi * x) / (K / 2)) for x in np.arange(N3)] ax.plot(np.arange(N3), d3, 'y', linewidth=2.0) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_1", "html": html}) fig, ax = plt.subplots(figsize=(6, 6)) sp = np.abs(np.fft.fft(d3)) ax.stem(np.arange(N3), sp, 'c') html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_2", "html": html}) return graphics
def lab_7_get_graphic_1(source_data, correct_answer): graphics = [] N0 = source_data["N0"] f0 = correct_answer["f0"] fm = correct_answer["fm"] m = correct_answer["m"] d1 = (1 + m * np.cos(2 * math.pi * fm * np.arange(0, N0) / N0)) * (np.cos( 2 * math.pi * f0 * np.arange(0, N0) / N0)) fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(np.arange(N0), d1) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_1_1", "html": html}) fig, ax = plt.subplots(figsize=(6, 6)) ax.stem(np.arange(N0), np.abs(np.fft.fft(d1)), 'c') html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_1_2", "html": html}) return graphics
def convert_to_html_and_open(fig): from mpld3 import fig_to_d3 html = fig_to_d3(fig) file=open('index.html','w') file.write('<style>body{background-color:#111111;color:#333333;font-size:10pt;font-family:sans-serif}') file.write('a{color:#444444;text-decoration:none;}</style>') file.write(html) file.write("How Far Can You See? <a href=https://github.com/rkeisler/nakedeye target='_blank'>made in python/d3</a> by <a href=https://twitter.com/RyanKeisler target='_blank'>@RyanKeisler</a> using <a href=https://twitter.com/jakevdp target='_blank'>@jakevdp's</a> awesome <a href=https://github.com/jakevdp/mpld3 target='_blank'>mpld3</a> library. work in progress. <br> if you don't see a map of stars, try refreshing.") file.close() # I'm not sure why, but this makes it run much faster and more smoothly. system("perl -pi -e 's/stroke-dasharray: 10,0/stroke-dasharray: 0,0/g' index.html") system('open index.html')
def lab_5_get_graphic_2(student_data, source_data): graphics = [] sl = np.array(student_data["student_sl"]) slc = np.array(student_data["student_slc"]) fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(sl) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_3", "html": html}) fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(slc) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_4", "html": html}) fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(np.fft.fft(sl)) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_5", "html": html}) fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(np.fft.fft(slc)) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_6", "html": html}) return graphics
def exec_file(self): print("running {0}".format(self.filename)) with disable_mpld3(): import matplotlib.pyplot as plt plt.close('all') my_globals = {'pl': plt, 'plt': plt} execfile(self.filename, my_globals) fig = plt.gcf() self.html = mpld3.fig_to_d3(fig) thumbfile = os.path.join(self.target_dir, self.pngfilename) fig.savefig(thumbfile) create_thumbnail(thumbfile, thumbfile)
def lab_2_get_graphics_3(source_data, correct_answer): graphics = [] f = np.array(correct_answer["f"]) Nk0 = len(f) N3 = int(source_data["N3"]) fig, ax = plt.subplots(figsize=(6, 6)) d9 = np.zeros(N3) for i in np.arange(1, Nk0 + 1): d9 = np.array(d9) + np.array( [math.cos(2 * math.pi * f[i - 1] * x / N3) for x in np.arange(N3)]) ax.plot(np.arange(N3), d9, 'y', linewidth=2.0) html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_5", "html": html}) fig, ax = plt.subplots(figsize=(6, 6)) sp = np.abs(np.fft.fft(d9)) ax.stem(np.arange(N3), sp, 'c') html = mpld3.fig_to_d3(fig) graphics.append({"id": "graphic_6", "html": html}) return graphics
def lab_3_get_graphic_1(student_data, source_data, correct_answer): b = student_data["student_filter"] N0 = len(b) y = np.append(student_data["student_signal"], np.zeros(N0 * 2)) S = int(correct_answer["S"]) y1_et = np.roll(y, (1) * S) ys1_et = y1_et + 0.5 * np.random.randn(1, 3 * N0)[0] z = signal.lfilter(b, 1, ys1_et) fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(ys1_et, linewidth=2.0) ax.plot(z, linewidth=2.0) html = mpld3.fig_to_d3(fig) graphic = {"id": "graphic_1", "html": html} return graphic
def combine_testplots(wildcard='test_plots/*.py', outfile='test_plots.html', d3_url=None): """Generate figures from the plots and save to an HTML file Parameters ---------- wildcard : string a regex matching files outfile : string the output HTML file for saving the results d3_url : string the URL of the d3 library to use. If not specified, a standard web address will be used. """ if isinstance(wildcard, basestring): filenames = glob.glob(wildcard) else: filenames = sum([glob.glob(w) for w in wildcard], []) fig_html = [] fig_names = [] for filename in filenames: dirname, fname = os.path.split(filename) modulename = os.path.splitext(fname)[0] if dirname not in sys.path: sys.path.append(dirname) f = __import__(modulename) if hasattr(f, 'main'): print "running {0}".format(filename) fig = f.main() fig_html.append(fig_to_d3(fig, d3_url)) fig_png = os.path.splitext(filename)[0] + '.png' fig.savefig(fig_png) fig_names.append("\n<div class='fig'><img src={0}>" "</div>\n".format(fig_png)) print "writing results to {0}".format(outfile) with open(outfile, 'w') as f: f.write(TEMPLATE.format(left_col="".join(fig_html), right_col="".join(fig_names)))
def lab_3_get_graphic_3(student_data, source_data): v = student_data["student_s"] for idx, v_value in enumerate(v): try: v[idx] = float(v_value) except: v[idx] = 0 s = np.array(source_data["s"]) fig, ax = plt.subplots(figsize=(6, 6)) # (markers, stemlines, baseline) = ax.stem(s, v, 'y') # ax.setp(markers, marker='D', markersize=10, markeredgecolor="orange", markeredgewidth=2) html = mpld3.fig_to_d3(fig) graphic = { "id": "graphic_3", "html": html, } return graphic
def plot_data(list_of_dicts, list_of_prices, list_of_scores): fig, ax = plt.subplots(subplot_kw=dict(axisbg='#f7f8f9')) N = len(list_of_prices) scatter = ax.scatter([i['score'] for i in list_of_dicts], [i['price'] for i in list_of_dicts], c=np.random.random(size=N), alpha=0.7, cmap=plt.cm.brg) ax.grid(color='white', linestyle='solid') ax.set_title("Lidl Wine vs. Score", size=30) ax.set_xlabel('Score', fontsize=20) ax.set_ylabel('Price (£)', fontsize=20) ax.set_xlim([81.5, 90]) labels = ['{0}'.format(i['name']) for i in list_of_dicts] tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels) mpld3.plugins.connect(fig, tooltip) html_string = mpld3.fig_to_d3(fig, template_type="simple") Html_file = open("results.html", "w") Html_file.write(html_string) Html_file.close() mpld3.show()
def lab_7_get_graphic_4(student_data, correct_answer): graphics = [] b_st = np.array(student_data["student_b"]) a_st = np.array(student_data["student_a"]) SD = np.array(correct_answer["SD"]) N1 = int(correct_answer["N1"]) z = signal.lfilter(b_st, a_st, SD) fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(np.arange(0, np.int(N1 * 8)), z[0:np.int(N1 * 8)]) ax.stem(np.arange(N1 / 2, N1 * 8, N1), np.take(z, np.arange(np.int(N1 / 2), np.int(N1 * 8), np.int(N1))), 'r', linewidth=3.0) html = mpld3.fig_to_d3(fig) graphics.append({ "id": "graphic_4_1", "html": html, }) return graphics
def descriptive_multi_cores(data): fig, ax = plt.subplots() lines=tools.file_lines(data[3]) ncol=tools.file_col(data[3])-1 outputs_files=data[1]+data[2] if lines==1: file = open(outputs_files, "w") writer=csv.writer(file, lineterminator=',') b=[[0 for x in xrange(6)] for x in xrange(ncol-2)] normality=[0 for x in xrange(1)] file.write("Variables,Class,N,Mean,Std_Dev,Variance,Max,Min,Coeff_Var,Interquartile,Normality_distrib,Confident_intervals_left,Confident_intervals_right\n") for col in xrange(ncol-2): a = tools.read_float_tab(data[3],col+2,1) b[col][0]=1 b[col][1]=float(a) b[col][2]=0 b[col][3]=0 b[col][4]=float(a) b[col][5]=float(a) file.write("%s,"%data[4][col+2]) file.write("%s,"%(os.path.splitext(data[2])[0])) file.write("%f,"%b[col][0]) file.write("%f,"%b[col][1]) file.write("%f,"%b[col][2]) file.write("%f,"%b[col][3]) file.write("%f,"%b[col][4]) file.write("%f,"%b[col][5]) file.write("100,") file.write("0,") file.write("0,") file.write("0,") file.write("0,\n") file.close() else: file = open(outputs_files, "w") writer=csv.writer(file, lineterminator=',') b=[[0 for x in xrange(11)] for x in xrange(ncol-2)] file.write("Variables,Class,N,Mean,Std_Dev,Variance,Max,Min,Coeff_Var,Interquartile,Normality_distrib,Confident_intervals_left,Confident_intervals_right\n") a=[0 for x in xrange(lines)] for col in xrange(ncol-2): for j in xrange(lines): a[j]=tools.read_float_tab(data[3],col+2,j) b[col][0]=float(len(a)) b[col][1]=float(np.mean(a)) b[col][2]=float(np.std(a, dtype=float)) b[col][3]=float(np.var(a, dtype=float)) b[col][4]=float(max(a)) b[col][5]=float(min(a)) if np.around(b[col][2],decimals=12) != 0.0: if float(len(a)) < 3: b[col][6]=float(abs((np.std(a)/np.mean(a))*100)) file.write("%s,"%data[4][col+2]) file.write("%s,"%(os.path.splitext(data[2])[0])) file.write("%f,"%b[col][0]) file.write("%f,"%b[col][1]) file.write("%f,"%b[col][2]) file.write("%f,"%b[col][3]) file.write("%f,"%b[col][4]) file.write("%f,"%b[col][5]) file.write("%f,"%b[col][6]) file.write("0,") file.write("0,") file.write("0,") file.write("0,\n") else: b[col][6]=float(abs((np.std(a)/np.mean(a))*100)) X=sort(a) upperQuartile = stats.scoreatpercentile(X,.75) lowerQuartile = stats.scoreatpercentile(X,.25) IQR = upperQuartile - lowerQuartile b[col][7]=float(IQR) normality=stats.shapiro(a) b[col][8]=float(normality[1]) b[col][9]=np.mean(a)-1.96*(np.std(a)/math.sqrt(len(a))) b[col][10]=np.mean(a)+1.96*(np.std(a)/math.sqrt(len(a))) file.write("%s,"%data[4][col+2]) file.write("%s,"%(os.path.splitext(data[2])[0])) file.write("%f,"%b[col][0]) file.write("%f,"%b[col][1]) file.write("%f,"%b[col][2]) file.write("%f,"%b[col][3]) file.write("%f,"%b[col][4]) file.write("%f,"%b[col][5]) file.write("%f,"%b[col][6]) file.write("%f,"%b[col][7]) file.write("%f,"%b[col][8]) file.write("%f,"%b[col][9]) file.write("%f,\n"%b[col][10]) if normality[1] >= 0.05: norm_distrib = np.linspace(-150,150,100) ax.set_title('Normality of %s class features'%os.path.splitext(data[2])[0]) ax.plot(norm_distrib,mlab.normpdf(norm_distrib,np.mean(a),math.sqrt(np.var(a))),label=data[4][col+2],ms=10, alpha=0.3) ax.legend(loc=2, ncol=1, bbox_to_anchor=(0, 0, 1, 0.7),fancybox=True,shadow=False,fontsize=5) ax.grid(color='lightgray', alpha=0.5) ax.patch.set_facecolor('white') else: b[col][6]=0 X=sort(a) upperQuartile = stats.scoreatpercentile(X,.75) lowerQuartile = stats.scoreatpercentile(X,.25) IQR = upperQuartile - lowerQuartile b[col][7]=float(IQR) b[col][8]=0 b[col][9]=np.mean(a)-1.96*(np.std(a)/math.sqrt(len(a))) b[col][10]=np.mean(a)+1.96*(np.std(a)/math.sqrt(len(a))) file.write("%s,"%data[4][col+2]) file.write("%s,"%(os.path.splitext(data[2])[0])) file.write("%f,"%b[col][0]) file.write("%f,"%b[col][1]) file.write("%f,"%b[col][2]) file.write("%f,"%b[col][3]) file.write("%f,"%b[col][4]) file.write("%f,"%b[col][5]) file.write("%f,"%b[col][6]) file.write("%f,"%b[col][7]) file.write("%f,"%b[col][8]) file.write("%f,"%b[col][9]) file.write("%f,\n"%b[col][10]) file.close() display_d3(fig) html = mpld3.fig_to_d3(fig) html_normality=data[1]+data[2]+".html" normality_display = open(html_normality, "w") normality_display.write("%s"%html) normality_display.close() plt.close()
"""Plot to test line styles""" import matplotlib.pyplot as plt import numpy as np from mpld3 import plugins, fig_to_d3 def main(): fig, ax = plt.subplots() colors = plt.rcParams['axes.color_cycle'] points = [] for i, color in enumerate(colors): points = ax.plot(i, 0, 'o', c=color) plugins.connect(fig, plugins.PointLabelTooltip(points[0], [color])) ax.set_xlim(-1, len(colors) + 1) return fig if __name__ == '__main__': fig = main() fig_to_d3(fig)
# Download d3 file locally d3_filename = 'd3.v3.min.js' if not os.path.exists(d3_filename): page = urllib2.urlopen('http://d3js.org/d3.v3.min.js') with open(d3_filename, 'w') as f: f.write(page.read()) # create a plot fig, ax = plt.subplots(subplot_kw={'axisbg':'#EEEEEE'}, facecolor='white') ax.plot(np.random.random(10), np.random.random(10), 'ob', markeredgecolor='lightblue', markersize=20, markeredgewidth=10, alpha=0.5) ax.plot(np.linspace(0.1, 0.9, 10), np.random.random(10), '-c', lw=5, alpha=0.5) ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_title('title', fontsize=20) ax.text(0.2, 0.85, "left", fontsize=18, ha='left') ax.text(0.2, 0.75, "center", fontsize=18, ha='center') ax.text(0.2, 0.65, "right", fontsize=18, ha='right') ax.grid(True, color='white', linestyle='solid') filename = "example.html" print "Writing output to {0}".format(filename) open(filename, 'w').write(fig_to_d3(fig, d3_filename)) #plt.show()
def lab_3_get_graphic_2(correct_answer, student_data, source_data, reload="True", is_signal=""): Ku_i_max = int(source_data["Ku"]) Ku_j_max = int(source_data["Ku"]) b = np.array(student_data["answer"]["student_filter"]) N0 = len(b) y = np.append(np.array(student_data["answer"]["student_signal"]), np.zeros(N0 * 2)) s_st = np.array(source_data["s"]) Ku_j = int(student_data["state"]["Ku_j"]) Ku_i = int(student_data["state"]["Ku_i"]) K = 13 # сделать не так there_is_signal_count = int(student_data["state"]["there_is_signal_count"]) there_is_no_signal_count = int( student_data["state"]["there_is_no_signal_count"]) if student_data["state"]["y2_s2"] is None: student_data["state"]["y2_s2"], correct_answer["s"] = get_y2_s2( Ku_j_max, Ku_i_max, N0, s_st, b, K, y) if is_signal == "there_is_signal": there_is_signal_count += 1 elif is_signal == "there_is_no_signal": there_is_no_signal_count += 1 else: pass if not student_data["state"]["Ku_done"]: student_data["state"]["there_is_signal_states"][Ku_j - 1] = { "there_is_signal_count": there_is_signal_count, "there_is_no_signal_count": there_is_no_signal_count } y2 = student_data["state"]["y2_s2"]["y2"][Ku_j - 1][Ku_i - 1] s2 = student_data["state"]["y2_s2"]["s2"][Ku_j - 1][Ku_i - 1] if not reload: if Ku_i == Ku_i_max: if Ku_j == Ku_j_max: student_data["state"]["Ku_done"] = True else: Ku_j += 1 Ku_i = 1 there_is_signal_count = 0 there_is_no_signal_count = 0 else: Ku_i += 1 student_data["state"]["Ku_j"] = Ku_j student_data["state"]["Ku_i"] = Ku_i student_data["state"]["there_is_signal_count"] = there_is_signal_count student_data["state"][ "there_is_no_signal_count"] = there_is_no_signal_count fig, ax = plt.subplots(figsize=(6, 6)) ax.plot(y2, linewidth=2.0) ax.plot(s2, linewidth=2.0) # ax.plot(np.arange(len(y)), np.full((len(y), 1), 0.707 * max(s2)), 'r') ax.plot(np.arange(len(y)), np.ones((len(y), 1)) * (0.707 * 130), 'r') ax.plot(np.arange(len(y)), np.ones((len(y), 1)) * (2 * math.sqrt(130)), 'b') html = mpld3.fig_to_d3(fig) graphic = {"id": "graphic_2", "html": html} return correct_answer, student_data, graphic
# itrace plots itrace = pd.read_csv(TRACEDIR + "/itrace.csv", index_col=False, names=["pid", "queue", "numContexts", "uop", "numUops", "cycleCount"]) # print itrace.head() num_pid = len(itrace["pid"].get_values()) unique_pids = set(itrace["pid"].get_values()) num_unique_pid = len(unique_pids) # print unique_pids fig, ax = plt.subplots(figsize=(10, 6)) # plt.scatter(itrace["cycleCount"], itrace["pid"], c=cm.hot(np.abs(y)), edgecolor='none') plt.scatter(itrace["cycleCount"], itrace["pid"], c=itrace["pid"]) ax.set_title("PID vs. Time") ax.set_xlabel("Time (cycles)", labelpad=10) ax.set_ylabel("PID", labelpad=10) plt.yticks(list(unique_pids)) plt.gca().get_yaxis().get_major_formatter().set_useOffset(False) plt.tight_layout() plt.savefig(PLOTDIR + "/vcore_exec2.png") # print mpld3.fig_to_d3(fig) # instructions executed by vcore fig, ax = plt.subplots(figsize=(10, 6)) sns.countplot(y="queue", hue="pid", data=itrace) ax.set_title("Virtual Core Thread Execution") ax.set_xlabel("Microinstructions Executed", labelpad=10) ax.set_ylabel("Virtual Core", labelpad=10) plt.savefig(PLOTDIR + "/vcore_exec.png") print mpld3.fig_to_d3(fig)
def main(): fig, ax = plt.subplots() N = 50 df = pd.DataFrame(index=range(N)) df['x'] = np.random.randn(N) df['y'] = np.random.randn(N) df['z'] = np.random.randn(N) labels = [] for i in range(N): label = df.ix[[i], :].T label.columns = ['Row {0}'.format(i)] labels.append(str(label.to_html())) # .to_html() is unicode, so make leading 'u' go away with str() points = ax.plot(df.x, df.y, 'o', color='k', mec='w', ms=15, mew=1, alpha=.9) ax.set_xlabel('x') ax.set_ylabel('y') tooltip = plugins.PointHTMLTooltip( points[0], labels, voffset=10, hoffset=10, css=css) plugins.connect(fig, tooltip) return fig if __name__ == '__main__': fig = main() print fig_to_d3(fig)
import numpy as np import matplotlib.pyplot as plt from mpld3 import fig_to_d3 fig, ax = plt.subplots() ax.plot(np.random.random(10), np.random.random(10), 'og') ax.plot(np.linspace(0.1, 0.9, 10), np.random.random(10), '-b', lw=5, alpha=0.2) ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_title('title', fontsize=20) ax.grid(True, color='lightgray', alpha=0.7) filename = "example.html" print "Writing output to {0}".format(filename) open(filename, 'w').write(fig_to_d3(fig))
import numpy as np import matplotlib.pyplot as plt from mpld3 import fig_to_d3 fig, ax = plt.subplots(subplot_kw={'axisbg':'#EEEEEE'}, facecolor='white') ax.plot(np.random.random(10), np.random.random(10), 'ob', markeredgecolor='lightblue', markersize=20, markeredgewidth=10, alpha=0.5) ax.plot(np.linspace(0.1, 0.9, 10), np.random.random(10), '-c', lw=5, alpha=0.5) ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_title('title', fontsize=20) ax.text(0.2, 0.85, "left", fontsize=18, ha='left') ax.text(0.2, 0.75, "center", fontsize=18, ha='center') ax.text(0.2, 0.65, "right", fontsize=18, ha='right') ax.grid(True, color='white', linestyle='solid') filename = "example.html" print "Writing output to {0}".format(filename) open(filename, 'w').write(fig_to_d3(fig, d3_location='d3.v3.min.js')) plt.show()