Gnuplot: Różnice pomiędzy wersjami

Z Wikibooks, biblioteki wolnych podręczników.
Usunięta treść Dodana treść
Linia 412: Linia 412:
</syntaxhighlight>
</syntaxhighlight>


=Dopasowanie danych do krzywej=
==Dopasowanie danych do krzywej==


Dopasowanie danych do krzywej (ang. curve fitting)<ref>[http://www.gnuplot.info/documentation.html gnuplot documentation : page 68 = fit]</ref>
Dopasowanie danych do krzywej (ang. curve fitting)<ref>[http://www.gnuplot.info/documentation.html gnuplot documentation : page 68 = fit]</ref>

Wersja z 13:01, 10 paź 2020

gnuplot – program do tworzenia wykresów w 2 i 3 wymiarach.


Jak korzystać z Gnuplota?

Sposoby:

  • bezpośredni
    • interaktywny
    • wywołanie programu z parametrami
  • za pomocą skryptów
  • poprzez inny program


  gnuplot -e "plot sin(x); pause -1"



skrypt basha

Skrypt powłoki Bash:

#!/usr/bin/gnuplot
reset
set terminal svg enhanced background rgb 'white'
set output "test.svg"
test

Kroki:

  • Zapisujemy skrypt jako ( nazwa przykładowa) test.sh.
  • nadajemy atrybut wykonywalności
  • uruchamiamy
 chmod +x test.sh
 ./test.sh


skrypt gnuplota

Jest to plik tekstowy zawierajacy polecenia gnuplota

Prykład:

reset
set terminal svg enhanced background rgb 'white'
set output "test.svg"
test


Kroki:

  • zapisujemy jako test.plt
  • uruchamiamy
 gnuplot "test.plt"

lub po uruchomieniu gnuplota:

 load "test.plt"


Skrypty gnuplota mają rozszerzenia:

  • plt
  • gp
  • gnu
  • pal ( palety, gradienty)

Ustawienia

 show variables all

Przykładowy wynik:

	All available variables:
	pi = 3.14159265358979
	GNUTERM = "wxt"
	NaN = NaN
	GPVAL_TERM = "wxt"
	GPVAL_TERMOPTIONS = "0 enhanced"
	GPVAL_OUTPUT = ""
	GPVAL_ENCODING = "default"
	GPVAL_MINUS_SIGN = "-"
	GPVAL_MICRO = "u"
	GPVAL_DEGREE_SIGN = "\302\260"
	GPVAL_VERSION = 5.0
	GPVAL_PATCHLEVEL = "7"
	GPVAL_COMPILE_OPTIONS = "-READLINE  +LIBEDITLINE  +HISTORY  \n-BACKWARDS_COMPATIBILITY  +BINARY_DATA  \n+GD_PNG  +GD_JPEG  +GD_TTF  +GD_GIF  +ANIMATION  \n-USE_CWDRC  +X11  +X11_POLYGON  +MULTIBYTE  +X11_EXTERNAL +USE_MOUSE  +HIDDEN3D_QUADTREE  \n+DATASTRINGS  +HISTOGRAMS  +OBJECTS  +STRINGVARS  +MACROS  +THIN_SPLINES  +IMAGE  +USER_LINETYPES +STATS +EXTERNAL_FUNCTIONS \n"
	GPVAL_MULTIPLOT = 0
	GPVAL_PLOT = 0
	GPVAL_SPLOT = 0
	GPVAL_TERMINALS = " cairolatex canvas cgm context corel domterm dumb dxf eepic emf emtex epscairo epslatex fig gif hpgl jpeg latex lua mf mp pcl5 pdfcairo png pngcairo postscript pslatex pstex pstricks qms svg tek40xx tek410x texdraw tgif tikz tkcanvas tpic unknown vttek wxt x11 xlib xterm "
	GPVAL_pi = 3.14159265358979
	GPVAL_NaN = NaN
	GPVAL_ERRNO = 1
	GPVAL_ERRMSG = "invalid command"
	GPVAL_PWD = "/home/a"
	GPVAL_LINENO = 0
	ARGC = 0
	ARG0 = ""


katalog

Sprawdzamy położenie roboczego katalogu:

 pwd


Sprawdzamy zawartość roboczego katalogu[1]

 system 'dir'

Terminal

Aktualny ( aktywny) terminal

  show terminal

Przykładowy wynik :

 terminal type is qt 0 font "Sans,9"


Możliwości terminala:

 set output "test.png" 
 test 



Aby zobaczyć listę dostępnych terminali napisz:

set terminal

Przykładowy wynik:

 Available terminal types:
       cairolatex  LaTeX picture environment using graphicx package and Cairo backend
           canvas  HTML Canvas object
              cgm  Computer Graphics Metafile
          context  ConTeXt with MetaFun (for PDF documents)
            corel  EPS format for CorelDRAW
             dumb  ascii art for anything that prints text
              dxf  dxf-file for AutoCad (default size 120x80)
            eepic  EEPIC -- extended LaTeX picture environment
              emf  Enhanced Metafile format
            emtex  LaTeX picture environment with emTeX specials
         epscairo  eps terminal based on cairo
         epslatex  LaTeX picture environment using graphicx package
              fig  FIG graphics language for XFIG graphics editor
              gif  GIF images using libgd and TrueType fonts
             gpic  GPIC -- Produce graphs in groff using the gpic preprocessor
          hp2623A  HP2623A and maybe others
           hp2648  HP2648 and HP2647
             hpgl  HP7475 and relatives [number of pens] [eject]
           imagen  Imagen laser printer
             jpeg  JPEG images using libgd and TrueType fonts
            latex  LaTeX picture environment
              lua  Lua generic terminal driver
               mf  Metafont plotting standard
              mif  Frame maker MIF 3.00 format
               mp  MetaPost plotting standard
             pcl5  HP Designjet 750C, HP Laserjet III/IV, etc. (many options)
         pdfcairo  pdf terminal based on cairo
              png  PNG images using libgd and TrueType fonts
         pngcairo  png terminal based on cairo
       postscript  PostScript graphics, including EPSF embedded files (*.eps)
          pslatex  LaTeX picture environment with PostScript \specials
            pstex  plain TeX with PostScript \specials
         pstricks  LaTeX picture environment with PSTricks macros
              qms  QMS/QUIC Laser printer (also Talaris 1200 and others)
            regis  REGIS graphics language
              svg  W3C Scalable Vector Graphics driver
          tek40xx  Tektronix 4010 and others; most TEK emulators
          tek410x  Tektronix 4106, 4107, 4109 and 420X terminals
          texdraw  LaTeX texdraw environment
             tgif  TGIF X11 [mode] [x,y] [dashed] ["font" [fontsize]]
             tikz  TeX TikZ graphics macros via the lua script driver
         tkcanvas  Tk/Tcl canvas widget [perltk] [interactive]
             tpic  TPIC -- LaTeX picture environment with tpic \specials
          unknown  Unknown terminal type - not a plotting device
            vttek  VT-like tek40xx terminal emulator
            xterm  Xterm Tektronix 4014 Mode

svg

 set terminal svg enhanced background rgb 'white'
 set output "test.svg"
 test

Dane

Format

liczby

Sprawdzamy aktualny format:


   show format


Przykładowy wynik

tic format is:
 x-axis: "% h"
 y-axis: "% h"
 x2-axis: "% h"
 y2-axis: "% h"
 z-axis: "% h"
 cb-axis: "% h"
 r-axis: "% h"


Jak widać standardowym formatem jest:

   "% h%"

czyli spacja potem liczba w formie wykładniczej


Dopuszczalne formaty w wersji 5:[2]

The acceptable formats (if not in time/date mode) are:
Format Explanation
%f floating point notation
%e or %E exponential notation; an "e" or "E" before the power
%g or %G the shorter of %e (or %E) and %f
%h or %H %g with "x10^{%S}" or "*10^{%S}" instead of "e%S". Compare with H in dat/time mode
%x or %X hex
%o or %O octal
%t mantissa to base 10
%l mantissa to base of current logscale
%s mantissa to base of current logscale; scientific power
%T power to base 10
%L power to base of current logscale
%S scientific power
%c character replacement for scientific power
%b mantissa of ISO/IEC 80000 notation (ki, Mi, Gi, Ti, Pi, Ei, Zi, Yi)
%B prefix of ISO/IEC 80000 notation (ki, Mi, Gi, Ti, Pi, Ei, Zi, Yi)
%P multiple of π

data/czas

Sprawdzamy format:

  show timefmt

Przykłądowy wynik:


  Default format for reading time data is "%d/%m/%y,%H:%M"

Tekst

  • Niestandardowe znaki [3][4]
  • wolne odpowiedniki czcionek własnościowych ( ang. proprietary fonts )
    • Times New Roman[5]
    • Arial
    • Courier New[6]

Rysowanie danych z pliku

Przygotowanie pliku z danymi

Gnuplot może być używany jako uniwersalny program do rysowania przez inne specjalistyczne programy.

Przygotowanie pliku z danymi w C

Ten program tworzy w swoim katalogu roboczym plik tekstowy data.txt zawierający dane w formacie[7] , który akceptuje gnuplot. Zawiera nagłówek poprzedzony znakiem "#", który przy rysowaniu jest ignorowany, oraz 2 kolumny liczb rozdzielone spacjami.

#include <stdio.h>
#include <stdlib.h>
int main(void) {
  int i;
  double x,y;
  char *output_filename="data.txt";
  FILE *output_file;
  output_file = fopen(output_filename, "w");  
  if (output_file  == NULL) {
    fprintf(stderr, "Nie moge otworzyc %s\n", output_filename);
    getchar();
    return 1;

  } else {
    /* nagłówek */
    fprintf(output_file,"%s %s      %s \n","#","x","y");
    y = 0.005;
    x = 0.0;
    /* 2 kolumny liczb rozdzielone spacjami */
    fprintf(output_file,"% 6.2f % 6.2f \n",x,y);
    for(i=0;i<5;++i) {
      x += y;
      /* 2 kolumny liczb rozdzielone spacjami */
      fprintf(output_file,"% 6.2f % 6.2f \n",x,y);
    }; /* for(i */
  }; /* if ((output_file ... else */
  fclose(output_file);

  fprintf(stderr,"file saved");
  getchar();
  
  
  return 0;
}

Zawartość pliku wygląda następująco:

# x      y 
 0.00   0.01 
 0.01   0.01 
 0.01   0.01 
 0.01   0.01 
 0.02   0.01 
 0.03   0.01

Przygotowanie pliku z danymi w MPSolve

W linii komend (bez uruchomiania gnuplota) wprowadzmy polecenie z opcją -Og:

./unisolve -Og Data/umand31.pol >Results/data.txt

Rysowanie

Przykładowy wykres zawierający dane z pliku oraz wykresy dwóch funkcji

Uruchom gnuplot:

gnuplot

i w linii komend wprowadź polecenie:

plot "data.txt" 

W cudzysłowie jest nazwa pliku, może być poprzedzona ścieżką.

Przykład:

gnuplot
set terminal png
set output "data.png"
set xlabel "x"
set ylabel "y"
set title "My title"
plot "data.txt"


Jeśli polik jest za duży i są problemy z pamięcią możemy użyć tylko niektórych danych , np co 10-ty wiersz:

 pl 'data.txt' u 1:2 every 10

Jeśli dane są w formacie naukowym to możemy je zmienić:

 set format y "%e";

Zobacz również:

  • rysowanie danych z kilku plików[8][9]

Rysowanie danych bez pliku

Możemy dane wprowadzić bezpośrednio, bez pliku, korzystając z: [10]


gnuplot << EOF
set terminal gif
set output 'plot1.gif'
plot '-' using 1:2
        1 10
        2 20
        3 32
        4 40
        5 50
        e
EOF


lub:

gnuplot -p <(echo -e 'plot "-"\n1 1\ne')

Dopasowanie danych do krzywej

Dopasowanie danych do krzywej (ang. curve fitting)[11]

Przykład: [12]

Podajemy wzór krzywej do której chcemy dopasować punkty zawarte w pliku dane.txt

f1(x) = a*x**3 + b*x**2 + c*x + d

wpisujemy parametry funkcji:

a=1
b=2
c=1
d=1

Znajdujemy dokładniejsze parametry:

fit f1(x) "dane.txt" using 1:2 via a, b, c, d

Wynik tekstowy podaje wiele danych opisujących nowe parametry i ich dopasowanie.


Rysujemy wykres krzywej i punktów:

plot "dane.txt", f1(x)

Wypisujemy nowe wartości parametrów:

 print a, b, c, d


Inny przykład: [13]

 f(x) = exp(-x*c)*b
fit f(x) "data.dat" u 1:2 via b,c
plot "data.dat" w p, f(x)

Kolor

Kolor [14]


Mysz

/*
http://www.gnuplot.info/files/gpReadMouseTest.c
gpReadMouseTest.c

Test piped communication and mouse readback with gnuplot.
This code is published under the GNU Public License.

This example demonstrates how to wait for a mouse press and get the
mouse button number and mouse position, from a graph in gnuplot.


Is this still true? Maybe no more necessary:
The weird thing is that the FIFO apparently wants to receive an
initial linefeed from gnuplot before it works. If you uncomment the
one line designated below, it still _may_ work (with emphasis on
"may"). Any ideas why?

*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

#define wait (printf("Press the 'any' key\n"), fgets(buf, 10, stdin));
#define GPFIFO "./gpio" /* any unique name */

int
main(int argc, char *argv[])
{
FILE  *gp, *gpin;
float mx = 0.0, my = 0.0;
int   mb = 0;
int   n;
char  buf[80];

/* Create a FIFO we later use for communication gnuplot => our program. */
if (mkfifo(GPFIFO, 0600)) {
    if (errno != EEXIST) {
	perror(GPFIFO);
	unlink(GPFIFO);
	return 1;
    }
}

if (NULL == (gp = popen("gnuplot","w"))) {
    perror("gnuplot");
    pclose(gp);
    return 1;
}
puts("Connected to gnuplot.\n");

/* Init mouse and redirect all gnuplot printings to our FIFO */
fprintf(gp, "set mouse; set print \"%s\"\n", GPFIFO);
fflush(gp);

/* Sometimes it was necessary to print \n from gnuplot to avoid a block.
   Probably it is no more necessary.
*/
#if 0
fprintf(gp, "print \"\\n\"\n");
fflush(gp);
#endif

/* Open the FIFO (where gnuplot is writing to) for reading. */
if (NULL == (gpin = fopen(GPFIFO,"r"))) {
    perror(GPFIFO);
    pclose(gp);
    return 1;
}

puts("FIFO open for reading.\n");


/* Now do the work. */
fprintf(gp, "plot sin(x)\n");
fflush(gp);

/* Do it 5 times. */
for (n=0; n<5; n++) {
    printf("\n%i/5. -- Click anywhere in the graph by mouse button 1.\n", n+1);
    fprintf(gp, "pause mouse 'Click mouse!'\n");
    fflush(gp);

    fprintf(stdout,"I'M HERE: %i\n", __LINE__);
    /* Let gnuplot write to coordinates values (to the FIFO). */
    fprintf(gp, "print MOUSE_X, MOUSE_Y, MOUSE_BUTTON\n");
    fflush(gp);

    fprintf(stdout,"I'M HERE: %i\n", __LINE__);
    /* Read from the FIFO. */
    fscanf(gpin, "%f %f %d", &mx, &my, &mb);
    fprintf(stdout,"I'M HERE: %i\n", __LINE__);
    printf("You pressed mouse button %d at x=%f y=%f\n", mb, mx, my);
/*  wait; */
}

fclose(gpin);
pclose(gp);
unlink (GPFIFO);
return 0;
}

/* eof gpReadMouseTest.c */

Problemy

util.c

cannot open file; output not changed
line 25: util.c: No such file or directory

Program ma problem z dostępem do wskazanego pliku/katalogu. Proszę sprawdzić gdzie chcemy zapisać wynikowy plik, prawdopodobnie tam jest błąd[15]

Bad data

Przyczyny:

  • otwieranie pliku z poleceniami gnuplota za pomocą złej komensy:
    • ( np. *.pal) za pomocą komendy : set palette file "jet.pal". Właściwy sposób to : load "jet.pal"
    • plot a nie load[16]
  • tekst w pliku z danymi[17]


Sprawdzamy w kodzie:

grep -nR --include *.c "bad data" 
src/stats.c:867:	 - using n:m = return two columns, skipping lines w/ bad data
src/stats.c:905:	      int_warn( NO_CARET, "bad data on line %d of file %s",
src/fit.c:1964:	    Eex2("bad data on line %d of datafile", df_line_number);
src/axis.c:302: * but even apart from that autoscaling bad data could cause a fault.

invalid character

  • w pliku jest znak którego nie powinno być, np. tab . Sprawdź plik za pomocą od

Pomoc

online

offline

terminal

Po uruchomieniu Gnuplota wpisujemy polecenie help lub help nazwa_polecenia. Np. :

 help show


Zobacz również

  • Maxima CAS - program który wykorzystuje gnuplot do tworzenia grafiki

Źródła

  1. stackoverflow question: in-gnuplot-for-windows-how-can-i-list-the-files-in-the-current-working-director
  2. Gnuplot 5 dokumentacja
  3. Gnuplot : ps_guide by Dick Crawford
  4. ymbols in html, latex and gnuplot, along with some acscii codes. by Mathew Peet
  5. askubuntu question: closest-alternative-to-times-new-roman?
  6. linux-font-equivalents-to-popular-web-typefaces by Jonathan Christopher
  7. gnuplot 4.2 doc: Format specifiers
  8. stackoverflow question: gnuplot-plotting-data-from-multiple-input-files-in-a-single-graph
  9. riptutorial : plotting-multiple-data-files
  10. Stackoverflow : Gnuplotting data without a textfile
  11. gnuplot documentation : page 68 = fit
  12. dopasowanie krzywej z Katedry Biotechnologii Środowiskowej UŚ
  13. stackoverflow question: fitting-a-curve-to-specific-data
  14. Wizualizacja danych - Gnuplot, dr hab. Bożena Woźna-SzczeŚniak
  15. stackoverflow questions : gnuplot-nested-do-loop-and-plotting-on-the-same-graph
  16. stackoverflow question: gnuplot-bad-data-on-line-1
  17. ubuntu forums: ] Gnuplot and openoffice
Commons
Commons