a quick guide to gnuplotpersonalpages.to.infn.it/~mignone/numerical_algorithms/gnuplot.pdf · xn y0...

18
A Quick Guide to Gnuplot Andrea Mignone Physics Department, University of Torino AA 2018-2019

Upload: others

Post on 13-Feb-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

AQuickGuidetoGnuplot

AndreaMignonePhysicsDepartment,UniversityofTorino

AA2018-2019

Page 2: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

WhatisGnuplot?•  Gnuplotisafree,command-driven,interactive,functionanddataplottingprogram,

providingarelativelysimpleenvironmenttomakesimple2Dplots(e.g.f(x)orf(x,y));

•  Itisavailableforallplatforms,includingLinux,MaxandWindows(http://www.gnuplot.info)

•  Tostartgnuplotfromtheterminal,simplytype

•  Toproduceasimpleplot,e.g.f(x)=sin(x)andf(x)=cos(x)^2

•  Bydefault,gnuplotassumesthattheindependent,or"dummy",variablefortheplotcommandis"x”(or“t”inparametricmode).

>gnuplot

gnuplot>plotsin(x)gnuplot>replot(cos(x))**2#Addanotherplot

Page 3: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

MathematicalFunctions•  Ingeneral,anymathematical

expressionacceptedbyC,FORTRAN,Pascal,orBASICmaybeplotted.TheprecedenceofoperatorsisdeterminedbythespecificationsoftheCprogramminglanguage.

•  GnuplotsupportsthesameoperatorsoftheCprogramminglanguage,exceptthatmostoperatorsacceptinteger,real,andcomplexarguments.

•  Exponentiationisdonethroughthe**operator(asinFORTRAN)

Page 4: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

Usingset/unset•  Theset/unsetcommandscanbeusedtocontrolsmanyfeatures,includingaxisrange

andtype,title,fonts,etc…•  Herearesomeexamples:

•  Immediatehelpisavailableinsidegnuplotviathe"help"command.

Command Descriptionsetxrange[0:2*pi] Limitthex-axisrangefrom0to2*pi,

setylabel“f(x)” Setsthelabelonthey-axis(sameas“setxlabel”)

settitle“MyPlot” Setstheplottitle

setlogy Setlogarithmicscaleonthey-axis(sameas“setlogx”)

unsetlogy Disablelogscaleonthey-axis

setkeybottomleft Positionthelegendinthebottomleftpartoftheplot

setxlabelfont",18" Changefontsizeforthex-axislabel(sameas“setylabel”)

setticfont",18" Changethemajor(labelled)ticsfontsizeonallaxes.

setsamples2500 Setthenumberofpointsusedtodrawafunction.

Page 5: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

PlottingDatafiles•  GnuplotcanalsoplotASCIIdatafileinmulticolumnformat;

•  Toplotamulti-columndatafileusingthe1stcolumnfortheabscissaandthe2ndcolumnastheordinate,use

•  Addasecondplotusing1st(=x)and3rd(=y)columns:

•  Ifthe“using”keywordisnotspecified,1stand2ndcolumnsareassumed:

gnuplot>plot“file.dat”using1:2

gnuplot>replot“file.dat”using1:3

file.dat

#Commentscanbeplacedherex0y0z0...x1y1z1.........xNyNzN…

gnuplot>plot“file.dat”

Page 6: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

ExampleofPlottingStyles•  Whenplottingdatafiles,Gnuplotusessymbols:

•  Tojoinsymbolswithlines,use

gnuplot>plot“file.dat”

gnuplot>plot“file.dat”withlines

Page 7: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

Datafilecontainingmoremultipledatasets•  [TODO]

Page 8: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

ProducingDatafilefromC++•  There’rebasicallytwowaystoproduceamulticolumnASCIIdatafilefromtheoutput

ofaC++program:1.  [Simple,notverygeneral]Byredirectingtheoutputofaprogramtofile:

The">"signisusedforredirectingtheoutputofaprogramtosomethingotherthanstdout(standardoutput,whichistheterminalbydefault).Similarly,the>>appendstoafileorcreatesthefileifitdoesn'texist.2.[Clever,moregeneral]Bycreatingthefileusingtheofstream(orsimilar)classinC++

./myprogram>myprogram.dat

#include<fstream>...ofstreamfdata;//declareOutputstreamclasstooperateonfilesfdata.open(“decay.dat”);//openoutputfile...for(...){fdata<<x<<""<<fx<<""<<..<<endl;//writetofile}fdata.close();//closefile

Page 9: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

Writing2DArrays•  Two-dimensionalarrays(suchasf[i][j])canbewritteninmulti-columnASCII

formatwiththeindexjchangingfasterandablankrecordsseparatingblockswithdifferentindexi:

x0 y0 f(0,0)x1 y0 f(1,0). . .xN y0 f(N,0) ß <empty line>x0 y1 f(0,1). . .xN y1 f(N,1) ß <empty line> ... ß <empty line> x0 yN f(0,N). . .xN yN f(N,N)

Page 10: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

Visualizing2DArrays

•  Gnuplotcanbeusedtodisplay2Darraysusingthe“splot”commandinsteadof“plot”.

•  Differentvisualizationsarepossible:

Surfaceplot

Contourplot

Coloredmaps

Page 11: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

gnuplot> set surfacegnuplot> set hidden3dgnuplot> splot “data.dat” u 1:2:3 w lines

gnuplot> set pm3d mapgnuplot> splot “data.dat” u 1:2:3

gnuplot> set contourgnuplot> unset surfacegnuplot> set view mapgnuplot> set cntrparam level 20gnuplot> splot "elliptic.dat" u 1:2:3 w lines

Page 12: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

Moreonpm3dmap•  Pm3Dmapisausefulplottingstyleforfunctionof2Dvariables.Sometips:

–  Exactaxisrangecanbeforcedusing

–  Gray-to-rgbmappingcanbesetthrough

–  Acolorgradientcanbedefinedandusedtogivethergbvalues.

gnuplot>setautoscalexfixmingnuplot>setautoscalexfixmaxgnuplot>setautoscaleyfixmingnuplot>setautoscaleyfixmaxgnuplot>splot“file.dat”

gnuplot>setpalettedefined

gnuplot>setpalettedefined(0"blue",1"white",2"yellow")

Page 13: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

CreatingAnimations•  Animationscanbebuiltusingthedofor[]{..}ingnuplot(v≥4.6)

•  Considerthefollowingexample(simple_animation1.gp):

•  Ifyourgnuplotsupport.png,.gifor.jpegterminal,imagescanbesavedtodisk:

omega=2.0*pi;ntot=250#Numberofframesinoneperioddt=1.0/ntot#Theincrementbetweenframesdofor[n=0:2*ntot]{t=n*dt#Timeplotsin(x-omega*t)pause0.1#pauseinseconds}

settermpng#Fromnowon,plotswillbedoneonpngterminal#andnotonscreenomega=2.0*pi;ntot=250#Numberofframesinoneperioddt=1.0/ntot#Theincrementbetweenframesdofor[n=0:2*ntot]{fname=sprintf("sin_%04d.png",n)#Filenamesetoutputfname#Redirectoutputtofilet=n*dt#Timeplotsin(x-omega*t)}

Page 14: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

CreatingAnimations:Datafiles•  AnimationscanalsobeproducedfromASCIIdatafileswrittenwithyourC++code.

•  Atrajectoryanimationcanbedone,forinstance,usingtheeverykeywordoftheplotcommand:

•  Examples:

plot'file'everyI:J:K:L:M:N

plot'file'every2#Plotevery2linesplot'file'every::3#Plotstartingfromthe3rdlineplot'file'every::3::15#Plotlines3-15

I J K L M NLineincrement

Datablockincrement

Firstline Firstdatablock

Lastline Lastdatablock

Page 15: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

Trajectory:2DAnimation•  Thefollowingscriptdemonstratehowatrajectorycanbeanimated:

•  AnimprovedversionaddstheSun(ingreen)andaredwake(takenfrom Animations/kepler*.*):

setxrange[-1:1]#Alwaysagoodideatosetyrange[-1:1]#fixtheaxisrangesetpointsize2#symbolsizesetstyleline2lcrgb'#0060ad'pt7#circledofor[ii=1:3762]{#Startplottingplot'keplerVV.dat'using2:3every::ii::iilinestyle2pause0.02}

...ntail=50#numberofpointstodrawinthetailninc=3#incrementbetweenframes#Addthesuninthecenterasagreenfilledcirclesetobjectcircleatfirst0,0sizescr0.01\fillcolorrgb'green’fillstylesoliddofor[ii=1:3762:ninc]{im=((ii-ntail)<0?1:ii-ntail)title=sprintf("Step=%d",ii)settitletitleplot'keplerVV.dat'using2:3every::ii::iilinestyle2,\'keplerVV.dat'using2:3every::im::iiwithlineslt1}

Page 16: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

Trajectory:3DAnimations•  Iftheparticle’strajectoryisnotconfinedtoaplane,thenyoucanmodifythescriptby

usingsetparametricandsplot(takenfromAnimations/spiral_anim.*)

setparametricsetxyplaneat0setgridsetpointsize2#symbolsizesetstyleline2lcrgb'#0060ad'pt7#circle#--Plotsetting--setxrange[-0.1:0.1]setyrange[-0.1:0.1]setzrange[0:2]nstop=990ntail=70ninc=3#incrementbetweenframessetview60,30sethidden3dfname="spiral_anim.dat”#datafilenamedofor[ii=1:nstop:ninc]{printiiim=((ii-ntail)<0?1:ii-ntail)splotfnameusing2:3:($4)every::ii::iilinestyle2,\fnameusing2:3:($4)every::im::iiwithlineslt1#Addshadowonthexyplanereplotfnameusing2:3:(0*$4)every::im::iiwithlineslt3}

Page 17: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

ManyParticlesAnimation•  Ifyouhavemanyparticlestravellingatdifferentenergies,youmayhaveseveral

datafiles,oneforeachtimet.•  Inthiscaseadifferentinputdata-fileisreadateachloopcycle:

•  SeeAnimations/nparts_anim.*.

setcbrange[0:35]#Fixthecolorbarrangesetpointsize1setstyleline2lcrgb'#0060ad'pt7#circlesetxlabel"x"font",18"setylabel"y"font",18"setticsfont",18"vmag(vx,vy,vz)=sqrt(vx*vx+vy*vy+vz*vz)#Defineusefulcolumn-functiondofor[n=0:100]{title=sprintf("Particlevelocitymagnitude,n=%d",n)#Titlestringsettitletitle_stringfont",18”fname=sprintf('particles.%04d.tab',n)#Datafilestringplotfnameusing2:3:(vx=$5,vy=$6,vz=$7,vmag(vx,vy,vz))\every1withpointsls2palette}

Page 18: A Quick Guide to Gnuplotpersonalpages.to.infn.it/~mignone/Numerical_Algorithms/gnuplot.pdf · xN y0 f(N,0) ß  x0 y1 f(0,1) ... Some tips: – Exact axis range can

ReferencesontheWeb•  ManytutorialsonGnuplotareavailableonline.

•  http://www.gnuplotting.org-Thiswebsitegivesmanyusefulexamplesonhowtocreatenicelookingplots.ThesectionGnuplotbasicsàPlottingdataexplainsmanydifferentwaystoplotdatafiles.

•  http://lowrank.net/gnuplot/index-e.html-Hereyoucanfindanicetutorial,explainingLegend,tics,label,2Dand3Dplottingandmuchmore.