def main(): from Gnuplot import Gnuplot, Data from time import sleep func = lambda x: 1.2*(x-2)**2 + 2*x + 10 ht = HomogenousTable.fromfunc(func, -10, 10, 10) it = InHomogenousTable.fromfunc(func, [-11,-7,-5,-3,-2,-1,0, 1,2,3,5,7,11]) it2 = InHomogenousTable.fromfunc(func, [-8,-5,-2,0, 2,5,8]) gp = Gnuplot(persist=1) x = linspace(-5,5,20) gp.plot(Data(x, func(x), with_='l'), Data(x, ht(x), title='ht'), Data(x, (1.2*ht + 2)(x), title='1.2*ht +2'), Data(x, it(x), title='it'), Data(x, it2(x), title='it2')) sleep(1) exit()
self.sock.send('START\r\n') def stopMeasurement(self): self.sock.send('STOP\r\n') def readVoltage(self): try: retval = self.sock.recv(1024000) except: retval = None return retval def close(self): self.sock.close() plt = Gnuplot.Gnuplot() configuration_text = open('exposure_control_config.txt', 'r').readlines() parameters = dict() for line in configuration_text: if ((line[0] != '#') & (line[0] != '\n') ): l = line.split() try: parameters[l[0].upper()] = float(l[2]) print 'Added float ', parameters[l[0].upper()], ' as entry for key ', l[0].upper() except: if line.find("\"") == -1: parameters[l[0].upper()] = l[2] print 'Added text variable ', parameters[l[0].upper()], ' as entry for key ', l[0].upper() else: parameters[l[0].upper()] = line[line.find("\"")+1:line.rfind("\"")]
def plot(self): g = Gnuplot.Gnuplot(persist=1) d = Gnuplot.Data(self.data(), with='lines lw 6')
import scipy.linalg import scipy.stats import Gnuplot import CrossSection import Geometry import fissionSource import arnoldiMC import powerMC import procOUTSN import gnuplotFile if __name__ == "__main__": VectorChart = Gnuplot.Gnuplot() # VectorChart("set yrange [:1.1]") amchistories = 1000 pmchistories = 1000 amciterations = 5 amcrestarts = 40 pmciterations = 50 bins = 10 halfwidth = 10 geo = Geometry.Geometry(bins, [[0, 2*halfwidth]]) xs = CrossSection.CrossSection(xS=0.5, nu=1.0, xF=0.5, xG=0) uSource = fissionSource.histogramSource(scipy.ones(bins), geo) # Arnoldi's Method
# NAV Plot pressure-density-temperature triples for granite #------------------------------------------------------------------------------- eos = EOSes[0] rho0 = eos.referenceDensity rhoMin, rhoMax = 0.9 * etamin * rho0, 1.1 * etamax * rho0 drho = (rhoMax - rhoMin) / 50 rho = [rhoMin + k * drho for k in range(50)] T = range(200, 1001, 100) P = [] for rhok in rho: for Tj in T: P.append( (rhok, Tj, eos.pressure(rhok, eos.specificThermalEnergy(rhok, Tj)))) Pplot = Gnuplot.Gnuplot() Pplot.xlabel("rho (kg/m^3)") Pplot.ylabel("T (K)") Pplot(" set grid") Pdata = Gnuplot.Data(P) Pplot.splot(Pdata, title="Pressure (Pa)") #------------------------------------------------------------------------------- # NAV Plot a P-rho curve for water at reference temperature #------------------------------------------------------------------------------- eos = EOSes[5] T0 = 320 rho0 = eos.referenceDensity rho = [rho0 + j * rho0 / 8000 for j in range(101)] P = [] for rhoj in rho:
if not steps is None: control.step(steps) else: control.advance(goalTime) control.dropRestartFile() #------------------------------------------------------------------------------- # Plot the final flaw distribution, if requested. #------------------------------------------------------------------------------- if plotFlaws and DamageModelConstructor is StochasticWeibullTensorDamageModel: from SpheralGnuPlotUtilities import generateNewGnuPlot import Gnuplot flaws = [x for x in damageModel.sortedFlaws()] f = [i / volume for i in xrange(len(flaws))] fans = [kWeibull * x**mWeibull for x in flaws] d = Gnuplot.Data(flaws, f, title="Simulation", inline=True) dans = Gnuplot.Data(flaws, fans, with_="lines", title="Analytic", inline=True) p = generateNewGnuPlot() p("set logscale xy") p("set key top left") p.plot(d) p.replot(dans) #------------------------------------------------------------------------------- # Compute the fragment properties and spit them out to a file. #------------------------------------------------------------------------------- ## import pickle
ofile = file(ofile_name, 'w') ofile.write('# file %s, %d draws with %d samples per draw #\n' % (ifile_name.split(os.sep)[-1], draws, sample_count)) ofile.write('# sigma^2 min avg max stddev compression #\n') for h in graph: ofile.write('%.8f %.2f %.2f %.2f %.2f %.2f\n' % tuple(h)) ofile.close() try: import Gnuplot except ImportError: print '\nCANNOT FIND GNUPLOT-PYTHON MODULE\n' sys.exit() #Gnuplot.GnuplotOpts.default_term='unknown' ### touch this if you encounter ### problems g = Gnuplot.Gnuplot(debug=0) g.title('file %s, %d draws with %d samples per draw' % (ifile_name.split(os.sep)[-1], draws, sample_count)) g('set style data lines') g.xlabel('sigma^2') g.ylabel('per cent') g.plot(Gnuplot.Data([(a[0], a[2]) for a in graph], title='avg')) g.replot(Gnuplot.Data([(m[0], m[1]) for m in graph], title='min')) g.replot(Gnuplot.Data([(M[0], M[3]) for M in graph], title='max')) g.replot(Gnuplot.Data([(s[0], s[4]) for s in graph], title='stddev')) g.replot(Gnuplot.Data([(c[0], c[5]) for c in graph], title='compression')) gfile_name = '%s-cross.ps' % (os.path.splitext(ifile_name)[0]) g.hardcopy(gfile_name, color=1)
potgiven.append([angle, float(y[j])]) XtX = transpose(x) * x XtY = transpose(x) * y b = linalg.inv(XtX) * XtY print 'rotor', i, files pot = [] for j in range(21): angle = (-60.0 + j * 120 / 20.0) * 2 * math.pi / 360.0 v = b[0] for k in range(5): v = v + b[k + 1] * cos((k + 1) * angle) + b[k + 6] * sin( (k + 1) * angle) pot.append([angle, v]) g = Gnuplot.Gnuplot() harmonics.write(str(float(b[0])) + '\n') for k in range(5): harmonics.write( str(float(b[k + 1])) + '\t' + str(float(b[k + 6])) + '\n') harmonics.write('\n') # g('set data style linespoints') # g.plot(potgiven,pot) # raw_input("Enter...") harmonics.write('\n')
#!/usr/bin/python import Gnuplot import time import numpy import rospy from std_msgs.msg import Float32 gp=Gnuplot.Gnuplot() plot_topic = rospy.get_param("~plot_topic", [('/eth0/receive', 'reveive'), ('eth0/transmit', 'transmit')]) max_y = rospy.get_param("~max_y", 1200000) data_scale = rospy.get_param("~data_scale", 0.001) data_rate = rospy.get_param("~data_rate", 100) period = rospy.get_param("~period", 120) drop_num = rospy.get_param("~drop_num", 10) #drop 9 topic out of 10 drop_index = [0 for i in range(len(plot_topic))] xrange = (period, 0) yrange = (0, (int)(max_y * data_scale)) xlabel = rospy.get_param("~x_label", "Time (s)") ylabel = rospy.get_param("~y_label", "Network Data Rates (kbps)") title = rospy.get_param("~title", "Network Status") plot_size = data_rate * period / drop_num y_list = [numpy.zeros(plot_size) for i in range(len(plot_topic))] x = numpy.arange(plot_size) / float(plot_size / period)
restartFileConstructor = restartFileConstructor, restartObjects = restartObjects) output('control') # Smooth the initial conditions. if restoreCycle: control.loadRestartFile(restoreCycle) else: control.smoothState(smoothIters) ################################################################################## # Advance to the end time. position1 = [] while control.time() < goalTime: control.advance(goalTime, 1000) position1.append(nodes1.positions[0][:]) xPosition1 = array([x[0] for x in position1]) yPosition1 = array([x[1] for x in position1]) # Plot the final state. import Gnuplot gdata = Gnuplot.Data(xPosition1, yPosition1, with='points') plot = Gnuplot.Gnuplot() plot.title = 'particle 1 position' plot.xlabel = 'x' plot.ylabel = 'y' plot.plot(gdata) plot('set size square') plot.refresh()
F = SimpelFunc2(LHS_x, RHS_x) #F = SimpelFunc3(LHS_x,RHS_x) # Find the minimum on the given interval. solver = fminbound(FuncToMinimize=F, Tol=Tol) (xmin, fmin) = solver.solve(Guess_x) # ------ Plotting ------- # xLeft = LHS_x dx = old_div((abs(RHS_x - LHS_x)), RefnVal) xVec = [] fVec = [] for i in range(RefnVal + 1): x = xLeft + i * dx Fval = F.getResidual(x) xVec.append(x) fVec.append(Fval) #print "x",xVec #print "s",sVec g = Gnuplot.Gnuplot(debug=1) g.title('Plot of Function') # (optional) g('set data style linespoints') # give gnuplot an arbitrary command d = Gnuplot.Data(numpy.array(xVec), numpy.array(fVec)) dmin = Gnuplot.Data(xmin, fmin) g.xlabel('x') g.ylabel('f(x)') g.plot(d, dmin) input('Please press return to continue...\n') print("Minimum at (x,f(x)) = (", xmin, ",", fmin, ")")
if G2.cfg['$EnableMocompCalc'] != 'off': # parse the average ground speed G2.cfg['$ProcAveGrndSpeed'] = '' if G2.parseParam(MocLog, 'Proc average ground speed', '$ProcAveGrndSpeed', 'cfg') != 0: ErrorExit('in parsing average ground speed from log') else: if G2.cfg[ '$AveGroundSpeed'] != 'null': # use radar config file value, if exists G2.cfg['$ProcAveGrndSpeed'] = G2.cfg['$AveGroundSpeed'] else: ErrorExit('AveGroundSpeed must be specified if MocompCalc is off') if G2.cfg[ '$EnablePlotMotionError'] == 'y': # make a pretty plot of the motion error g = Gnuplot.Gnuplot() g.xlabel('Track Time (secs)') g.ylabel('Motion Error (m)') data = Gnuplot.File(MocTxtFile, title='Motion error', extras='lines') g.plot(data) g.hardcopy(filename=MocPsFile, color=1, fontsize=20) time.sleep(5.0) del g, data print '(Motion error plot written to postscipt file)' #----------------------------- # Find DC offsets and I/Q ratio if G2.cfg['$EnableSniffDC'] == 'y': SDCRowsToProc = int(0.2 * int(G2.cfg['$InputPRIsToProc'])) SDCStartCol = int(0.25 * int(G2.cfg['$RngBinsToProc'])) SDCColsToProc = int(0.5 * int(G2.cfg['$RngBinsToProc']))
long_rho = longGrid.getValue(z) / longGrid.getStepZ() long_arr.append((z, long_rho)) long_grad_arr = [] for ix in range(nStep + 1): z = ix * bunch_length / nStep - bunch_length / 2.0 long_grad_rho = longDerivGrid.getValue(z) long_grad_arr.append((z, long_grad_rho)) #------------------------------------------------- #this is the example of using the Gnuplot package #Comment this part if you do not have this package installed. #------------------------------------------------- import Gnuplot gLong = Gnuplot.Gnuplot() gLong.title('Long Density as a function of z') gLong('set style data lines') gLong.plot(long_arr) gLongGrad = Gnuplot.Gnuplot() gLongGrad.title('Derivative of Long. Density ') gLongGrad('set style data lines') gLongGrad.plot(long_grad_arr) raw_input('Please press return to stop:\n') #------------------------------------------------- print "Stop." #orbit_mpi.finalize("Test is done!")
#!/usr/bin/env python from numpy import * import Gnuplot g = Gnuplot.Gnuplot() g.title('My Systems Plot') g.xlabel('Date') g.ylabel('Response') g('set auto x') g('set term png') g('set out "output.png"') g('set timefmt "%s"') g('set xdata time') g('set xtic rotate by 45 scale 1 font ",2"') g('set key noenhanced') g('set format x "%H:%M:%S"') g('set grid') databuff = Gnuplot.File("repo", using='1:2', title="test") g.plot(databuff)
#!/usr/bin/env python # # Author: Patrick Hung (patrickh @caltech) # Copyright (c) 1997-2016 California Institute of Technology. # Copyright (c) 2016-2017 The Uncertainty Quantification Foundation. # License: 3-clause BSD. The full license text is available at: # - https://github.com/uqfoundation/mystic/blob/master/LICENSE from mystic.tools import getch import Gnuplot, numpy g = Gnuplot.Gnuplot(debug=1) g.clear() x = numpy.arange(-4, 4, 0.01) y = numpy.cos(x) y2 = numpy.cos(2 * x) kwds = {'with': 'line'} g.plot(Gnuplot.Data(x, y, **kwds)) getch('next: any key') g.plot(Gnuplot.Data(x, y2, **kwds)) getch('any key to quit') # end of file
def create_temporary_image(recid, kind_of_graphe, data_file, x_label, y_label, origin_tuple, y_max, docid_list, graphe_titles, intervals, gnuplot=False): """From a temporary file, draw a gnuplot graph The arguments are as follows: recid - record ID kind_of_graph - takes one of these values : "citation" ,"download_history", "download_users" All the commons gnuplot commands for these cases, are written at the beginning After the particular commands dependaing of each case are written. data_file - Name of the temporary file which contains the gnuplot datas used to plot the graph. This file is organized into one or more sets of 2 columns. First column contains x coordinates, and second column contains y coordinates. Each set is separated from the others by two blank lines. x_label - Name of the x axe. y_label - Name of the y axe. origin_tuple - Reference coordinates for positionning the graph. y_max - Max value of y. Used to set y range. docid_list - In download_history case, docid_list is used to plot multiple curves. graphe_titles - List of graph titles. It's used to name the curve in the legend. intervals - x tics location and xrange specification""" if gnuplot or CFG_BIBRANK_SHOW_CITATION_GRAPHS == 1: if cfg_gnuplot_available == 0: return (None, None) #For different curves color_line_list = ['4', '3', '2', '9', '6'] #Gnuplot graphe object g = Gnuplot.Gnuplot() #Graphe name: file to store graph graphe_name = "tmp_%s_%s_stats.png" % (kind_of_graphe, recid) g('set terminal png small') g('set output "%s/img/%s"' % (CFG_WEBDIR, graphe_name)) len_intervals = len(intervals) len_docid_list = len(docid_list) # Standard options g('set size 0.5,0.5') g('set origin %s,%s'% (origin_tuple[0], origin_tuple[1])) if x_label == '': g('unset xlabel') else: g.xlabel(s = x_label) if x_label == '': g('unset ylabel') else: g.ylabel(s = y_label) g('set bmargin 5') #let a place at the top of the graph g('set tmargin 1') #Will be passed to g at the end to plot the graphe plot_text = "" if kind_of_graphe == 'download_history': g('set xdata time') #Set x scale as date g('set timefmt "%m/%Y"') #Inform about format in file .dat g('set format x "%b %y"') #Format displaying if len(intervals) > 1 : g('set xrange ["%s":"%s"]' % (intervals[0], intervals[len_intervals-1])) y_offset = max(3, float(y_max)/60) g('set yrange [0:%s]' %str(y_max + y_offset)) if len_intervals > 1 and len_intervals <= 12: g('set xtics rotate %s' % str(tuple(intervals)))#to prevent duplicate tics elif len_intervals > 12 and len_intervals <= 24: g('set xtics rotate "%s", 7776000, "%s"' % (intervals[0], intervals[len_intervals-1])) #3 months intervalls else : g('set xtics rotate "%s",15552000, "%s"' % (intervals[0], intervals[len_intervals-1])) #6 months intervalls if len_docid_list <= 1: #Only one curve #g('set style fill solid 0.25') if len(intervals)<=4: plot_text = plot_command(1, data_file, (0, 0), "", "imp", color_line_list[0], 20) else: plot_text = plot_command(1, data_file, (0, 0), "", "linespoint", color_line_list[0], 1, "pt 26", "ps 0.5") elif len_docid_list > 1: #Multiple curves if len(intervals)<=4: plot_text = plot_command(1, data_file, (0, 0), graphe_titles[0], "imp", color_line_list[0], 20) else: plot_text = plot_command(1, data_file, (0, 0), graphe_titles[0], "linespoint", color_line_list[0], 1, "pt 26", "ps 0.5") for d in range(1, len_docid_list): if len(intervals)<=4: plot_text += plot_command(0, data_file, (d, d) , graphe_titles[d], "imp", color_line_list[d], 20) else : plot_text += plot_command(0, data_file, (d, d) , graphe_titles[d], "linespoint", color_line_list[d], 1, "pt 26", "ps 0.5") if len(intervals)>2: plot_text += plot_command(0, data_file, (len_docid_list, len_docid_list), "", "impulses", 0, 2 ) plot_text += plot_command(0, data_file, (len_docid_list, len_docid_list), "TOTAL", "lines", 0, 5) elif kind_of_graphe == 'download_users': g('set size 0.25,0.5') g('set xrange [0:4]') g('set yrange [0:100]') g('set format y "%g %%"') g("""set xtics ("" 0, "CERN\\n Users" 1, "Other\\n Users" 3, "" 4)""") g('set ytics 0,10,100') g('set boxwidth 0.7 relative') g('set style fill solid 0.25') plot_text = 'plot "%s" using 1:2 title "" with boxes lt 7 lw 2' % data_file else: #citation g('set boxwidth 0.6 relative') g('set style fill solid 0.250000 border -1') g('set xtics rotate') if len(intervals) > 1: g('set xrange [%s:%s]' % (str(intervals[0]), str(intervals[len_intervals-1]))) else: g('set xrange [%s:%s]' % (str(intervals[0]-1), str(intervals[0]+1))) g('set yrange [0:%s]' %str(y_max+2)) plot_text = """plot "% s" index 0:0 using 1:2 title "" w steps lt %s lw 3""" % (data_file, color_line_list[1]) g('%s' % plot_text) elif CFG_BIBRANK_SHOW_CITATION_GRAPHS == 2: graphe_name = "tmp_%s_%s_stats.html" % (kind_of_graphe, recid) out = """ <!--[if IE]><script language="javascript" type="text/javascript" src="%(site)s/js/excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="%(site)s/js/jquery.min.js"></script> <script language="javascript" type="text/javascript" src="%(site)s/js/jquery.flot.min.js"></script> <script language="javascript" type="text/javascript" src="%(site)s/js/jquery.flot.selection.min.js"></script> <script id="source" language="javascript" type="text/javascript"> document.write('<div style="float:left"><div id="placeholder" style="width:500px;height:400px"></div></div>'+ '<div id="miniature" style="float:left;margin-left:20px;margin-top:50px">' + '<div id="overview" style="width:250px;height:200px"></div>' + '<p id="overviewLegend" style="margin-left:10px"></p>' + '</div>'); $(function () { function parseDate(sdate){ var div1 = sdate.split('/'); if(div1.length == 1){ return new Date(sdate).getTime() - (new Date().getTimezoneOffset() * 60 * 1000) ;} else{ return new Date(div1[1], div1[0]-1).getTime() - (new Date().getTimezoneOffset() * 60 * 1000) ;} } function getData() {""" % \ {'site' : CFG_SITE_URL} # Set options data = open(data_file, 'r') tics = "" lines = 'lines' if kind_of_graphe == 'download_history': if len(intervals) > 1 : tics += 'xaxis: { mode:"time",min:parseDate("%s"),max:parseDate("%s")},'\ % (intervals[0], intervals[len(intervals)-1]) tics += """yaxis: { tickDecimals : 0 }, """ options = """var options ={ %s """% tics if len(intervals)<=4: options += """series: { bars: { show: true }, points: { show: false } }, """ lines = 'bars' else: options += """series: { lines: { show: true }, points: { show: false } }, """ if len(docid_list) > 1: #Multiple curves options += """, legend: { show : true}""" for d in range(1, len_docid_list): out += """var d%s = ["""%d first = 0 while True: x,_,y = data.readline().partition(' ') if y == '': data.readline() break if first == 0: first = 1 else: out += ', ' out += '[parseDate("%s"),%s]' % \ (x,y.strip()) out += """]; """ out += """ return [d1]; } """ elif kind_of_graphe == 'download_users': tics += """xaxis: { ticks: ['', "CERN\\n Users", '', "Other\\n Users", '']}, yaxis: { min: 0, max: 100},""" options = """var options ={ %s series: { bars: { show: true }, points: { show: false } }, legend: { show : false}, """%tics lines = 'bars' else: #citation tics += """xaxis: { mode:"time",min:parseDate("%s"),max:parseDate("%s")}, yaxis: { min: 0, max: %s},""" % (str(intervals[0]), str(intervals[len(intervals)-1]), str(y_max+2)) options = """var options ={ %s series: { lines: { show: true }, points: { show: true } }, legend: { show : false}, """ % tics if docid_list is None or len(docid_list) <= 1: #Only one curve out += """var d1 = [""" first = 0 for line in data: x,_,y = line.partition(' ') if y == '': break if first == 0: first = 1 else: out += ', ' out += '[parseDate("%s"),%s]' % \ (x,y.strip()) out += """]; return [d1]; } """ options += """grid: { hoverable: true, clickable: true }, selection: { mode: "xy" } };""" # Generate also the gnuplot image in case javascript is disabled gnuplotimage = create_temporary_image(recid, kind_of_graphe, data_file, x_label, y_label, origin_tuple, y_max, docid_list, graphe_titles, intervals, gnuplot=True) # Write the plot method in javascript out += """%s var startData = getData(); var plot = $.plot($("#placeholder"), startData, options); var overview = $.plot($("#overview"), startData, { legend: { show: true, container: $("#overviewLegend") }, series: { %s: { show: true, lineWidth: 1 }, shadowSize: 0 }, %s grid: { color: "#999" }, selection: { mode: "xy" } }); """% (options, lines, tics) # Tooltip and zoom out += """ function showTooltip(x, y, contents) { $('<div id="tooltip">' + contents + '</div>').css( { position: 'absolute', display: 'none', top: y - 5, left: x + 10, border: '1px solid #fdd', padding: '2px', 'background-color': '#fee', opacity: 0.80 }).appendTo("body").fadeIn(200); } var previousPoint = null; $("#placeholder").bind("plothover", function (event, pos, item) { if (item) { if (previousPoint != item.datapoint) { previousPoint = item.datapoint; $("#tooltip").remove(); var y = item.datapoint[1]; showTooltip(item.pageX, item.pageY, y); } } else { $("#tooltip").remove(); previousPoint = null; } }); $("#placeholder").bind("plotclick", function (event, pos, item) { if (item) { plot.highlight(item.series, item.datapoint); } }); $("#placeholder").bind("plotselected", function (event, ranges) { // clamp the zooming to prevent eternal zoom if (ranges.xaxis.to - ranges.xaxis.from < 0.00001){ ranges.xaxis.to = ranges.xaxis.from + 0.00001;} if (ranges.yaxis.to - ranges.yaxis.from < 0.00001){ ranges.yaxis.to = ranges.yaxis.from + 0.00001;} // do the zooming plot = $.plot($("#placeholder"), startData, $.extend(true, {}, options, { xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }, yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to } })); // don't fire event on the overview to prevent eternal loop overview.setSelection(ranges, true); }); $("#overview").bind("plotselected", function (event, ranges) { plot.setSelection(ranges); }); }); </script>""" # Support for disabled javascript out += "<noscript>" out += """<img src='%s/img/%s' align="center" alt="">"""% (CFG_SITE_URL, gnuplotimage[0]) out += "</noscript>" open(CFG_WEBDIR + "/img/" + graphe_name, 'w').write(out) data.close() else: graphe_name = "tmp_error.html" open(CFG_WEBDIR + "/img/" + graphe_name, 'w').write("Error, select a correct format") return (graphe_name, data_file)
import numpy import Gnuplot import math import sys import time sys.path.append("../bin") import h5py_array import datagroup_utils #sys.argv[1] = 'exp_-20xx_simple.hdf' with h5py_array.H5pyArray(sys.argv[1]) as file: rawData = file.require_group("/Raw Data") eigenDatas = file.require_group("Eigen Data") for data in eigenDatas: if raw_input('Calculate for %s (y/n)?' % data) == 'y': #plot this data eigenData = eigenDatas[data] vect = eigenData['eigenvectors'].value val = eigenData['eigenvalues'].value domain = eigenData['domain'] g = Gnuplot.Gnuplot() g('set style data lines') for i, v in enumerate(vect.swapaxes(0, 1)): g.title("abs(eigenvalue) = %f" % val[i]) g.plot(Gnuplot.Data( domain, numpy.real(v))) #ect[:,float(sys.argv[2])]))) time.sleep(0.1) raw_input("press key to finish")
def main(tmpFileName): skipped_lines_count = 0 skipped_lines_index = [] gf = open(tmpFileName, 'w') try: in_file = open(sys.argv[1]) xtic = int(sys.argv[2]) col_list = sys.argv[3].split(',') title = 'set title "' + sys.argv[4] + '"' ylabel = 'set ylabel "' + sys.argv[5] + '"' ymin = sys.argv[6] ymax = sys.argv[7] img_file = sys.argv[8] img_size = sys.argv[9] except Exception: stop_err("Check arguments\n") try: int(col_list[0]) except Exception: stop_err('You forgot to set columns for plotting\n') for i, line in enumerate(in_file): valid = True line = line.rstrip('\r\n') if line and not line.startswith('#'): row = [] try: fields = line.split('\t') for col in col_list: row.append(str(float(fields[int(col) - 1]))) except Exception: valid = False skipped_lines_count += 1 skipped_lines_index.append(i) else: valid = False skipped_lines_count += 1 skipped_lines_index.append(i) if valid and xtic > 0: row.append(fields[xtic - 1]) elif valid and xtic == 0: row.append(str(i)) if valid: gf.write('\t'.join(row)) gf.write('\n') if skipped_lines_count < i: # Prepare 'using' clause of plot statement g_plot_command = ' ' # Set the first column if xtic > 0: g_plot_command = "'%s' using 1:xticlabels(%s) ti 'Column %s', " % ( tmpFileName, str(len(row)), col_list[0]) else: g_plot_command = "'%s' using 1 ti 'Column %s', " % (tmpFileName, col_list[0]) # Set subsequent columns for i in range(1, len(col_list)): g_plot_command += "'%s' using %s t 'Column %s', " % ( tmpFileName, str(i + 1), col_list[i]) g_plot_command = g_plot_command.rstrip(', ') yrange = 'set yrange [' + ymin + ":" + ymax + ']' try: g = Gnuplot.Gnuplot() g('reset') g('set boxwidth 0.9 absolute') g('set style fill solid 1.00 border -1') g('set style histogram clustered gap 5 title offset character 0, 0, 0' ) g('set xtics border in scale 1,0.5 nomirror rotate by 90 offset character 0, 0, 0' ) g('set key invert reverse Left outside') if xtic == 0: g('unset xtics') g(title) g(ylabel) g_term = 'set terminal png tiny size ' + img_size g(g_term) g_out = 'set output "' + img_file + '"' if ymin != ymax: g(yrange) g(g_out) g('set style data histograms') g.plot(g_plot_command) except Exception: stop_err("Gnuplot error: Data cannot be plotted") else: sys.stderr.write( 'Column(s) %s of your dataset do not contain valid numeric data' % sys.argv[3]) if skipped_lines_count > 0: sys.stdout.write( '\nWARNING. You dataset contain(s) %d invalid lines starting with line #%d. These lines were skipped while building the graph.\n' % (skipped_lines_count, skipped_lines_index[0] + 1))
def create_temporary_gnuplot_image(kind_of_graph, data_file, x_label, y_label, origin_tuple, y_max, docid_list, graphe_titles, intervals, dest): #For different curves color_line_list = ['4', '3', '2', '9', '6'] #Gnuplot graphe object g = Gnuplot.Gnuplot() g('set terminal png small') g('set output "%s"' % dest) len_intervals = len(intervals) len_docid_list = len(docid_list) # Standard options #g('set size 0.5,0.5') g('set origin %s,%s' % (origin_tuple[0], origin_tuple[1])) if x_label == '': g('unset xlabel') else: g.xlabel(s=x_label) if x_label == '': g('unset ylabel') else: g.ylabel(s=y_label) g('set bmargin 5') #let a place at the top of the graph g('set tmargin 1') #Will be passed to g at the end to plot the graphe plot_text = "" if kind_of_graph == 'download_history': g('set xdata time') # Set x scale as date g('set timefmt "%m/%Y"') # Inform about format in file .dat g('set format x "%b %y"') # Format displaying if len(intervals) > 1: g('set xrange ["%s":"%s"]' % (intervals[0], intervals[len_intervals - 1])) y_offset = max(3, float(y_max) / 60) g('set yrange [0:%s]' % str(y_max + y_offset)) if len_intervals > 1 and len_intervals <= 12: g('set xtics rotate %s' % str(tuple(intervals))) # to prevent duplicate tics elif len_intervals > 12 and len_intervals <= 24: g('set xtics rotate "%s", 7776000, "%s"' % (intervals[0], intervals[len_intervals - 1])) # 3 months intervalls else: g('set xtics rotate "%s",15552000, "%s"' % (intervals[0], intervals[len_intervals - 1])) # 6 months intervalls if len_docid_list <= 1: # Only one curve #g('set style fill solid 0.25') if len(intervals) <= 4: plot_text = plot_command(1, data_file, (0, 0), "", "imp", color_line_list[0], 20) else: plot_text = plot_command(1, data_file, (0, 0), "", "linespoint", color_line_list[0], 1, "pt 26", "ps 0.5") elif len_docid_list > 1: # Multiple curves if len(intervals) <= 4: plot_text = plot_command(1, data_file, (0, 0), graphe_titles[0], "imp", color_line_list[0], 20) else: plot_text = plot_command(1, data_file, (0, 0), graphe_titles[0], "linespoint", color_line_list[0], 1, "pt 26", "ps 0.5") for d in range(1, len_docid_list): if len(intervals) <= 4: plot_text += plot_command(0, data_file, (d, d), graphe_titles[d], "imp", color_line_list[d], 20) else: plot_text += plot_command(0, data_file, (d, d), graphe_titles[d], "linespoint", color_line_list[d], 1, "pt 26", "ps 0.5") if len(intervals) > 2: plot_text += plot_command(0, data_file, (len_docid_list, len_docid_list), "", "impulses", 0, 2) plot_text += plot_command(0, data_file, (len_docid_list, len_docid_list), "TOTAL", "lines", 0, 5) elif kind_of_graph == 'download_users': g('set xrange [0:4]') g('set yrange [0:100]') g('set format y "%g %%"') g("""set xtics ("" 0, "CERN\\n Users" 1, "Other\\n Users" 3, "" 4)""") g('set ytics 0,10,100') g('set boxwidth 0.7 relative') g('set style fill solid 0.25') plot_text = 'plot "%s" using 1:2 title "" with boxes lt 7 lw 2' % data_file else: # citation g('set boxwidth 0.6 relative') g('set style fill solid 0.250000 border -1') g('set xtics rotate') if len(intervals) > 1: g('set xrange [%s:%s]' % (str(intervals[0]), str(intervals[len_intervals - 1]))) else: g('set xrange [%s:%s]' % (str(intervals[0] - 1), str(intervals[0] + 1))) g('set yrange [0:%s]' % str(y_max + 2)) plot_text = """plot "% s" index 0:0 using 1:2 title "" w steps lt %s lw 3""" % ( data_file, color_line_list[1]) g('%s' % plot_text)
maxdySPHerror0 = max([abs(x) for x in errdySPH0]) maxdySPHerror1 = max([abs(x) for x in errdySPH1]) print "Maximum error in uncorrected SPH: %g" % maxdySPHerror0 print "Maximum error in corrected SPH: %g" % maxdySPHerror1 #------------------------------------------------------------------------------- # Plot the things. #------------------------------------------------------------------------------- if graphics: from SpheralGnuPlotUtilities import * import Gnuplot xans = [positions[i].x for i in xrange(nodes1.numInternalNodes)] dansdata = Gnuplot.Data(xans, [x.xx for x in dyans.internalValues()], with_="lines", title="Answer", inline=True) dSPH0data = Gnuplot.Data(xans, [x.xx for x in dfSPH0.internalValues()], with_="points", title=HydroChoice + " (uncorrected)", inline=True) dSPH1data = Gnuplot.Data(xans, [x.xx for x in dfSPH1.internalValues()], with_="points", title=HydroChoice + " (corrected)", inline=True) errdSPH0data = Gnuplot.Data(xans, errdySPH0.internalValues(), with_="points", title=HydroChoice + " (uncorrected)", inline=True) errdSPH1data = Gnuplot.Data(xans,
################ # Main program # ################ opts, solvers = parse_cmdline(sys.argv[1:]) metrics = MetricsClass(solvers, opts) pprofs = RatioClass(metrics) nprobs = metrics.nprobs nsolvs = metrics.nsolvs # Create a performance profile graph persist_val = (opts.term in ('X11', 'x11')) g = Gnuplot.Gnuplot(persist=persist_val, debug=0) # Generate the x-axis data ydata = ma.arange(nprobs + 1) * (1.0 / nprobs) # Set the x-axis ranges maxrat = pprofs.maxrat + 1.0e-3 if opts.logscale: g('set logscale x %f' % opts.logscale) minrat = 1 else: minrat = 0 # asm4: if opts.xlimit < maxrat: maxrat = opts.xlimit
def plot(plotitems=[], options=[], outfig=-1, filename=None): """ - Purpose Plot a function. - Synopsis fig = plot(plotitems=[], options=[], outfig=-1, filename=None) - Input plotitems: Default: []. List of plotitems. options: Default: []. List of options. outfig: Default: -1. Integer. Figure number. 0 creates a new figure. filename: Default: None. String. Name of the PNG output file. - Output fig: Figure number. - Examples # import numpy # x = numpy.arange(0, 2*numpy.pi, 0.1) plot([[x]]) y1 = numpy.sin(x) y2 = numpy.cos(x) opts = [['title', 'Example Plot'],\ ['grid'],\ ['style', 'linespoints'],\ ['xlabel', '"X values"'],\ ['ylabel', '"Y Values"']] y1_plt = [x, y1, None, 'sin(X)'] y2_plt = [x, y2, 'lines', 'cos(X)'] # # plotting two graphs using one step fig1 = plot([y1_plt, y2_plt], opts, 0) # # plotting the same graphs using two steps fig2 = plot([y1_plt], opts, 0) fig2 = plot([y2_plt], opts, fig2) # # first function has been lost, lets recover it opts.append(['replot']) fig2 = plot([y1_plt], opts, fig2) """ import Gnuplot import numpy newfig = 0 if (plotitems == 'reset'): _figs[0] = None _figs[1:] = [] return 0 if len(plotitems) == 0: # no plotitems specified: replot current figure if _figs[0]: outfig = _figs[0] g = _figs[outfig] g.replot() return outfig else: #assert 0, "plot error: There is no current figure\n" print "plot error: There is no current figure\n" return 0 # figure to be plotted if ((outfig < 0) and _figs[0]): # current figure outfig = _figs[0] elif ((outfig == 0) or ((outfig == -1) and not _figs[0])): # new figure newfig = 1 outfig = len(_figs) elif outfig >= len(_figs): #assert 0, 'plot error: Figure ' + str(outfig) + 'does not exist\n' print 'plot error: Figure ' + str(outfig) + 'does not exist\n' return 0 #current figure _figs[0] = outfig # Gnuplot pointer if newfig: if len(_figs) > 20: print '''plot error: could not create figure. Too many PlotItems in memory (20). Use plot('reset') to clear table''' return 0 g = Gnuplot.Gnuplot() _figs.append(g) else: g = _figs[outfig] # options try: options.remove(['replot']) except: g.reset() try: #default style g('set data style lines') for option in options: if option[0] == 'grid': g('set grid') elif option[0] == 'title': g('set title "' + option[1] + '"') elif option[0] == 'xlabel': g('set xlabel ' + option[1]) elif option[0] == 'ylabel': g('set ylabel ' + option[1]) elif option[0] == 'style': g('set data style ' + option[1]) else: print "plot warning: Unknown option: " + option[0] except: print "plot warning: Bad usage in options! Using default values. Please, use help.\n" # Plot items: item[0]=x, item[1]=y, item[2]=style for item in plotitems: try: title = None style = None x = numpy.ravel(item[0]) if len(item) > 1: # y axis specified y = numpy.ravel(item[1]) if len(item) > 2: # style specified style = item[2] if len(item) > 3: title = item[3] else: # no y axis specified y = x x = numpy.arange(len(y)) g.replot(Gnuplot.Data(x, y, title=title, with_=style)) except: g.reset() if newfig: _figs.pop() #assert 0, "plot error: Bad usage in plotitems! Impossible to plot graph. Please, use help.\n" print "plot error: Bad usage in plotitems! Impossible to plot graph. Please, use help.\n" return 0 # PNG file if filename: g.hardcopy(filename, terminal='png', color=1) fig = outfig return fig
def plotCandidate(fil_file, sample, filter, dm): verbose = False res_x = '800' res_y = '600' resolution = res_x + 'x' + res_y # change to temp dir workdir = tempfile.mkdtemp() # check the file exists dmlist = DM_LIST try: fptr = open(dmlist, 'r') except IOError: print "ERROR: cannot open dmlist " + dmlist os.rmdir(workdir) sys.exit(1) else: # determine the dm index in the file that matches dm_idx = 0 lines = fptr.readlines() for line in lines: line = line.strip() if float(line) > dm: break dm_idx += 1 if verbose: sys.stderr.write("DM index: " + str(dm_idx) + " from DM=" + str(dm) + "\n") out_nsamp = 64 out_dmcount = 32 fscrunch = 32 os.chdir(workdir) cmd = "candidate_profiler " + \ fil_file + " " + \ dmlist + " " + \ str(sample) + " " + \ str(filter) + " " + \ str(dm_idx) + " " + \ str(out_nsamp) + " " + \ str(out_dmcount) + " " + \ str(fscrunch) in_nsamps = 0 sys.stderr.write(cmd + "\n") p = os.popen(cmd) for line in p.readlines(): line = line.strip() sys.stderr.write(line + "\n") parts = line.split("=") if (parts[0] == "in_nsamps"): in_nsamps = int(parts[1]) p.close() # Generate plots if verbose: sys.stderr.write("Generating plot...\n") g = Gnuplot.Gnuplot(debug=0) g('set terminal pngcairo enhanced font "arial,10" size ' + res_x + ', ' + res_y) g('set output "candidate_' + resolution + '.tmp.png"') if verbose: sys.stderr.write("Writing plots to candidate_" + resolution + ".tmp.png\n") g('set multiplot') g('set bmargin 0; set tmargin 0; set lmargin 0; set rmargin 0') g('TM = 0.06') g('BM = 0.06') g('LM = 0.06') g('RM = 0.06') g('NX = 2') g('NY = 2') g('SX = 1./NX - (LM + RM)') g('SY = 1./NY - (TM + BM)') snrdm_plot = SNRDMPlot(g) snrtime_plot = SNRTimePlot(g) freqtime_plot = FreqTimePlot(g, dm, in_nsamps) snrdm_plot.plot(workdir + "/snr_dm.dat") snrtime_plot.plot(workdir + "/snr_time.dat") freqtime_plot.plot(workdir + "/freq_time.dat") g('unset multiplot') g.close() img_file = open(workdir + '/candidate_' + resolution + '.tmp.png') try: bytes_read = img_file.read() content = bytes_read finally: img_file.close() os.chdir('/') if verbose: sys.stderr.write("Files written to " + workdir + "\n") os.remove(workdir + "/snr_dm.dat") os.remove(workdir + "/snr_time.dat") os.remove(workdir + "/freq_time.dat") os.remove(workdir + "/dm_time.pgm") os.remove(workdir + '/candidate_' + resolution + '.tmp.png') os.rmdir(workdir) return content
#!/usr/bin/env python import Gnuplot plotter = Gnuplot.Gnuplot(persist=1) plotter('set data style lines') # plot x^2 : x for range 0..20 rd = range(20 + 1) data = [(r, r * r) for r in rd] print(data) plotter.plot(data) data = [(r, r / 4) for f in rd] plotter.addplot(data)
x_i = -10 d_x = 0.01 while x_i < x: y += gauss(x_i) * d_x x_i += d_x return y def f(x, l): x = -abs(x - (l / 2.0)) x = x / 10.0 + 8 return gauss_int(x) def taps(n): x = [] for i in range(n): y = f(i, n) x.append(y) return x if __name__ == '__main__': import Gnuplot, Gnuplot.funcutils g = Gnuplot.Gnuplot(debug=1) g('set style data lines') g.plot(taps(input("n="))) a = raw_input("")
else: print "error" class0 = np.array(class0) class1 = np.array(class1) func = "(-1)*" \ + "("+ str(A) +")" \ + "/" \ + "("+str(B)+")" \ + "*x+" \ + "(-1)*" \ + "("+str(C)+")" \ + "/" + "("+str(B)+")" print func #if __name__ == "__main__": g = Gnuplot.Gnuplot(debug=1) g.title('SVM') # (optional) g('set data style linespoints') d0 = Gnuplot.Data(class0, title = "Class 0") d1 = Gnuplot.Data(class1, title = "Class 1") d2 = Gnuplot.Func(func, title = "Separating Plane") g.plot(d0, d1, d2) raw_input()
index = index + 1 + topics[index + 1:].index(topic) graph_time[index].append(t.secs - startsec + t.nsecs * 0.000000001) graph_data[index].append( eval("msg" + topicdata[index]) * scales[index]) num += 1 if num < 20: print index, "msg" + topicdata[index], eval("msg" + topicdata[index]) #print graph_data finally: bag.close() import Gnuplot plot_data = [] for i in range(len(data)): plot_data.append( Gnuplot.Data(graph_time[i], graph_data[i], title=titles[i])) gp = Gnuplot.Gnuplot(persist=1) gp("set grid") if x_range: tmp_str = "gp(\"set xr[" + str(x_range[0]) + ":" + str( x_range[1]) + "]\")" exec(tmp_str) if y_range: tmp_str = "gp(\"set yr[" + str(y_range[0]) + ":" + str( y_range[1]) + "]\")" exec(tmp_str) gp("set style data lines") gp("set key opaque box") if size: tmp_str = "gp(\"set tics font 'Times," + str(size) + "'\")" exec(tmp_str)
self.ylength()+v.ylength())) def __sub__(self, v): return Vector(self.start, Coord(self.xlength()-v.xlength(),\ self.ylength()-v.ylength())) def __float__(self): return [[self.start.x, self.start.y],[self.end.x, self.end.y]] def __init__(self, start, end): self.start = start self.end = end def plot(data): d = Gnuplot.Data(data[0],with='lines lw 6') g = Gnuplot.Gnuplot(persist=1) g.plot(d) for i in data: d.append(i.data()) g.replot(i) class Source: speaker_y_guide = 3 Listener = Coord(0, 0) Speakers = { 'left': Coord(-1.5, speaker_y_guide),\ 'right': Coord(1.5, speaker_y_guide) } Room = Size(4, 50) front = (Room.depth/2)-Speakers['left'].y back = -(Room.depth/2)+Speakers['left'].y sspeed = 344