Gnuplot: Różnice pomiędzy wersjami

Z Wikibooks, biblioteki wolnych podręczników.
Usunięta treść Dodana treść
Linia 293: Linia 293:
Kolor <ref>[http://www.wozna.org/students/2016-2017/Gnuplot/Gnuplot08.pdf Wizualizacja danych - Gnuplot, dr hab. Bożena Woźna-SzczeŚniak]</ref>
Kolor <ref>[http://www.wozna.org/students/2016-2017/Gnuplot/Gnuplot08.pdf Wizualizacja danych - Gnuplot, dr hab. Bożena Woźna-SzczeŚniak]</ref>
* [[Gnuplot/NazwyKolorów|nazwy]]
* [[Gnuplot/NazwyKolorów|nazwy]]

==Palette czyli gradient koloru ==
Sprawdzamy jaki mamy standardowy gradient kolorów (tradycyjny pm3d (czarny-niebieski-czerwony-żółty):

show palette

Otrzymujemy:
palette is COLOR
rgb color mapping by rgbformulae are 7,5,15
figure is POSITIVE
all color formulae ARE NOT written into output postscript file
allocating ALL remaining color positions for discrete palette terminals
Color-Model: RGB
gamma is 1.5

Wykres składowych koloru otrzymamy:

test palette<ref>/src/command.c</ref>
[[Grafika:RGB_profiles_of_the_color_palette.gif|thumb|right|Standardowy gradient w Gnuplocie]]
Możemy to zapisać do pliku png:

set terminal png
set output 'p.png'
test palette


gdzie :
* NTSC
** gray value : calculated using NTSC coefficients to map RGB onto a grayscale<ref>[http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/POYNTON1/ColorFAQ.html#RTFToC9 Poynton's Color FAQ by Charles Poynton]</ref>
** the NTSC luminance, which corresponds to the Y channel in the YIQ model. It indicates the result if the color were displayed on a black-and-white TV screen<ref>[https://livebook.manning.com/book/gnuplot-in-action-second-edition/appendix-d/75 https://livebook gnuplot-in-action-second-edition by P K Janert]</ref>
** ważona suma liniowych składników RGB<ref>[[:w:en:Luma_(video)|Luma_(video) w ang wikipedii]]</ref> <math>Y = 0.2126 R + 0.7152 G + 0.0722 B</math>

<source lang=c>
//from function test_palette_subcommand from command.c
ntsc = 0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b;
</source>

Sprawdzamy paletę :
show palette gradient
color mapping *not* done by defined gradient.

Polecenie

set palette

przywraca standardowe ustawienia :

<source lang=c>
// color.c
void
init_color()
{
/* initialize global palette */
sm_palette.colorFormulae = 37; /* const */
sm_palette.formulaR = 7;
sm_palette.formulaG = 5;
sm_palette.formulaB = 15;
sm_palette.positive = SMPAL_POSITIVE;
sm_palette.use_maxcolors = 0;
sm_palette.colors = 0;
sm_palette.color = NULL;
sm_palette.ps_allcF = FALSE;
sm_palette.gradient_num = 0;
sm_palette.gradient = NULL;
sm_palette.cmodel = C_MODEL_RGB;
sm_palette.Afunc.at = sm_palette.Bfunc.at = sm_palette.Cfunc.at = NULL;
sm_palette.colorMode = SMPAL_COLOR_MODE_RGB;
sm_palette.gamma = 1.5;
}

</source>

===file===
Składnia

set palette file '<filename>' {datafile-modifiers}

gdzie:
* filename jest to nazwa pliku palety zawierającego kolumny z danymi. Nie jest to plik z rozszerzeniem pal zawierajacy polecenia gnuplota
* data-modifiers jest to opcjonalny składnik służacy do wybierania elementów z palety( tabeli). Przykład: 'using ($1/255):($2/255):($3/255)'

Polecenie `set palette file` odpowiada poleceniu [[Gnuplot#defined|set palette defined]] a dane są wczytywane z pliku filename.

Sprawdzamy zawartość pomocy:

help set palette file

Przypadki użycia
* plik tekstowy ( gpf nie pal, który wczytujemy za pomocą polecenia load)
* plik binarny
* dane wczytywane z linii poleceń

====Plik tekstowy====
Składnia:

set palette file 'palette.txt' using ($1/255):($2/255):($3/255) # Read in a palette of RGB triples each in range [0,255]

W pliku mogą być:
* 4 kolumny: gray, R, G, B
* trzy kolumny: R, G, B




<source lang = gnuplot>
# http://soliton.vm.bytemark.co.uk/pub/cpt-city/arendal/arctic.gpf
set palette file "arctic.gpf"
set terminal png
set output "arctic.png"
test palette
</source>


Zbiory plików tekstowych gpf
* [http://soliton.vm.bytemark.co.uk/pub/cpt-city/index.html cpt-city ]: "Gnuplot Palette File (with gpf extension) in the RGB colour-space" ( 4 kolumny)
* pliki map programu Fractint ( 3 kolumny )
** [https://archive.org/details/ALLMAPS_ZIP Fractint [213 Map Files<nowiki>]</nowiki>]
** [http://www.krajzewicz.de/blog/free-color-palettes.php Daniel Krajzewicz: free-color-palettes]
** [https://github.com/rm-hull/webrot/tree/master/resources/private/maps webrot LUT maps]
set palette file "Skydye07.map" using ($1/255):($2/255):($3/255) # Read in a palette of RGB triples each in range [0,255]

====plik binarny ====

Składnia
set palette file "palette.bin" binary record=64 using 1:2:3 # put 64 triplets of R,G,B doubles into file palette.bin and load


====linia komend====
Możemy użyć tego polecenia do wprowadzenie tabeli kolorów w linii komend:
* zamiast nazwy koloru podajemy "-"
* wprowadzmy tabelę
* kończymy literą e

<source lang=gnuplot>
# Equidistant rainbow (blue-green-yellow-red) palette
set palette model RGB file "-"
0 0 1
0 1 0
1 1 0
1 0 0
e
</source>

<source lang=gnuplot>
# cpt-city/ma/gray/grayscale01a 0 … 100, continuous, RGB, 3 segments
set palette file "-"
0.00000 0.00000 0.00000 0.00000
0.35010 0.93333 0.93333 0.93333
0.75000 0.80000 0.80000 0.80000
1.00000 0.66667 0.66667 0.66667
e
</source>

===cubehelix===
[[Plik:Cubehelix gnuplot palette.png|mały|prawo|Cubehelix gnuplot palette]]
Rodzina palet kolorów opracowana przez D A Green (2011)<ref>[https://arxiv.org/abs/1108.5083 A colour scheme for the display of astronomical intensity images by D. A. Green]</ref> w której kolor (odcień) zmienia się wzdłuż standardowego koła kolorów, a jednocześnie intensywność rośnie monotonicznie, gdy wartość szarości zmienia się od 0 do 1.

Zalety:
* drukuje równie dobrze w kolorze i czerni/bieli<ref>[https://ifweassume.blogspot.com/2013/05/cubehelix-or-how-i-learned-to-love.html cubehelix-or-how-i-learned-to-love by James Davenport]</ref>

W kodzie:

<source lang=c>
// color.h: t_sm_palette typedef struct (Declaration of smooth palette, i.e. palette for smooth colours)
/* control parameters for the cubehelix palette scheme */
double cubehelix_start; /* offset (radians) from colorwheel 0 */
double cubehelix_cycles; /* number of times round the colorwheel */
double cubehelix_saturation; /* color saturation */

</source>

===gamma===

Składnia:

set palette gamma <gamma>

Ustawia współczynnik gamma na wartość <gamma>

Standardowa wartość współczynnika gamma = 1.5

Przykłady:<ref>[http://gnuplot.sourceforge.net/demo_5.5/pm3dgamma.html gnuplot 5.5 demo pm3dgamma]</ref>

set palette gamma 1.25


Gamma korekcja innymi metodami:<ref>[http://gensoft.pasteur.fr/docs/gnuplot/5.0.4/node302.html gnuplot 5.0.4 : gamma]</ref>

set palette model RGB
set palette functions gray**0.64, gray**0.67, gray**0.70


lub:

<source lang=gnuplot>
gamma = 2.2
color(gray) = gray**(1./gamma)
set palette model RGB functions color(gray), color(gray), color(gray) # A gamma-corrected black and white palette
</source>


W stosunku do palet szarych zamiast

set palette defined ( 0 0 0 0, 1 1 1 1 )

możemy użyć :
set palette defined ( 0 0 0 0, 0.5 .73 .73 .73, 1 1 1 1 )


Zobacz w kodzie:
<source lang=c>
// color.h
/* gamma for gray scale and cubehelix palettes only */
double gamma;
</source>

===gray/color===



Ustawienie szarej palety kolorów
set palette gray

przy standarowych ustawieniach odpowiada to :

set palette gray positive gamma 1.5 # nieliniowa

Jeśli chcemy otrzymać liniową palete to ustawiamy gamma na 1.0:

set palette gray gamma 1.0 # liniowa plaeta



Powrót do kolorowej palety:

set palette color


Zobacz też color modes:

<source lang=c>
//color.h
/*
* color modes
*/
typedef enum {
SMPAL_COLOR_MODE_NONE = '0',
SMPAL_COLOR_MODE_GRAY = 'g', /* grayscale only */
SMPAL_COLOR_MODE_RGB = 'r', /* one of several fixed transforms */
SMPAL_COLOR_MODE_FUNCTIONS = 'f', /* user defined transforms */
SMPAL_COLOR_MODE_GRADIENT = 'd', /* interpolated table:
* explicitly defined or read from file */
SMPAL_COLOR_MODE_CUBEHELIX = 'c'
} palette_color_mode;
</source>

===model/functions===

Składnia:
<source lang=gnuplot>
set palette functions <R>,<G>,<B>
set palette model { RGB | HSV | CMY | YIQ | XYZ }
</source>
może być łączone:<ref>[http://gnuplot.sourceforge.net/docs_4.2/node218.html gnuplot 4.2 docs: Palette/Functions]</ref>

set palette model HSV functions gray, 1, 1 # full color hsv = rainbow
set palette model XYZ functions gray**0.35, gray**0.5, gray**0.8 # black to gold

<source lang=gnuplot>
gamma = 2.2
color(gray) = gray**(1./gamma)
set palette model RGB functions color(gray), color(gray), color(gray) # A gamma-corrected black and white palette
</source>


Definicje
* gray jest zmienną przyjmującą wartości od 0 do 1

===rgbformulae===

Składnia:

<source lang=bas>
set palette rgbformulae <r>,<g>,<b>
</source>

skrócona postać :

set palette rgb r,g,b



r, g i b są to funkcje odpowiadające za obliczenie każdej ze składowej koloru.
(mimo że nazwy składowych są R,G oraz B to ich znaczenie jest zależne od [[w:Przestrzeń barw| modelu koloru]], tzn. w modelu HSV R będzie oznaczało H). Mamy do dyspozycji 37 wbudowanych funkcji ponumerowanych od 0 do 36 (liczby ujemne dają odwrócony gradient).
Możemy je wyświetlić:

show palette rgbformulae

Otrzymamy:

* there are 37 available rgb color mapping formulae:
0: 0 1: 0.5 2: 1
3: x 4: x^2 5: x^3
6: x^4 7: sqrt(x) 8: sqrt(sqrt(x))
9: sin(90x) 10: cos(90x) 11: |x-0.5|
12: (2x-1)^2 13: sin(180x) 14: |cos(180x)|
15: sin(360x) 16: cos(360x) 17: |sin(360x)|
18: |cos(360x)| 19: |sin(720x)| 20: |cos(720x)|
21: 3x 22: 3x-1 23: 3x-2
24: |3x-1| 25: |3x-2| 26: (3x-1)/2
27: (3x-2)/2 28: |(3x-1)/2| 29: |(3x-2)/2|
30: x/0.32-0.78125 31: 2*x-0.84 32: 4x;1;-2x+1.84;x/0.08-11.5
33: |2*x - 0.5| 34: 2*x 35: 2*x - 0.5
36: 2*x - 1
* negative numbers mean inverted=negative colour component
* thus the ranges in `set pm3d rgbformulae' are -36..36


Kod znajdziemy w: gnuplot/src/getcolor.c/GetColorValueFromFormula

[[Grafika:P hot.gif|thumb|right|Gorący gradient]]
[[Grafika:P hot inv.gif|thumb|right|Odwrócony gorący gradient]]
[[Plik:Gnuplot linear gray gradient.png|mały|prawo|Odrócony liniowy gradinet szarości]]

Standardowo są wybrane funkcje nr 7 dla składowej czerwonej, 5 dla składowej zielonej i 15 dla niebieskiej.
Możemy wybrać inny zestaw, na przykład proponowany w dokumentacji zestaw "gorący" ( ang. hot =black-red-yellow-white):

set palette rgbformulae 21,22,23

albo odwrócony gorący gradient:
set palette rgbformulae -21,-22,-23

lub odwrócony liniowy gradient szarości

set palette rgbformulae -3,-3,-3 # 1-x, 1-x, 1-x


Przykłady przestrzenie RGB:<ref>[http://soc.if.usp.br/manual/gnuplot-doc/htmldocs/rgbformulae.html#rgbformulae gnuplot-doc : rgbformulae]</ref>

7,5,15 ... traditional pm3d (black-blue-red-yellow)
3,11,6 ... green-red-violet
23,28,3 ... ocean (green-blue-white); try also all other permutations
30,31,32 ... color printable on gray (black-blue-violet-yellow-white)
33,13,10 ... rainbow (blue-green-yellow-red)
34,35,36 ... AFM hot (black-red-yellow-white)
Pełna paleta HSV

3,2,2 ... red-yellow-green-cyan-blue-magenta-red

=== defined ===
Składnia:

set palette defined { ( <gray1> <color1> {, <grayN> <colorN>}... ) }

gdzie

<pre>
<color> := { <r> <g> <b> | ’<color-name>’ | ’#rrggbb’ }
</pre>

Paleta jest zbudowana poprzez liniową interpolację między wartościami określonymi w definicji.
Przykłady:
<source lang=gnuplot>
set palette defined (0 "dark-green", 1 "green", 1 "yellow", 4 "red")
test palette
</source>
Otrzymujemy nieciągły gradient.

Za pomocą 2 kolorów otrzymujemy ciągły gradient ( liniowy) pomiędzy bielą ( 1 1 1) a czernią ( 0 0 0 )

<source lang=gnuplot>
set palette model RGB
set output "gray.png"
set palette defined (0 1 1 1, 1 0 0 0) # <r> <g> <b>
test palette
</source>
Inna równowazna składnie polecena set palette:

<source lang=gnuplot>
set palette defined ( 0 "white", 1 "black") # ’<color-name>’
set palette defined ( 0 "#ffffff", 1 "#000000") # ’#rrggbb’
</source>
[[Plik:Gnuplot linear gray gradient.png|mały|prawo|Gnuplot linear gray gradient]]


<source lang=gnuplot>
# Approximate the default palette used by MATLAB:
set pal defined (1 '#00008f', 8 '#0000ff', 24 '#00ffff', 40 '#ffff00', 56 '#ff0000', 64 '#800000')
</source>
[[Plik:Matlab gradient.png|mały|prawo|Matlab gradient]]



Dane możemy wprowadzić z
* linii poleceń
* z pliku palety pal

load 'a.pal'


Przykład pliku tekstowego pal:

<source lang=gnuplot>
# jet.pal with 4 columns
set palette defined (0 0.0 0.0 0.5, \
1 0.0 0.0 1.0, \
2 0.0 0.5 1.0, \
3 0.0 1.0 1.0, \
4 0.5 1.0 0.5, \
5 1.0 1.0 0.0, \
6 1.0 0.5 0.0, \
7 1.0 0.0 0.0, \
8 0.5 0.0 0.0 )
</source>

<source lang=gnuplot>
# ColorBrewer Accent
# https://github.com/Gnuplotting/gnuplot-palettes/blob/master/accent.pal
# for use with qualitative/categorical data
# provides 8 colors, 4 pale and 4 saturated
# compatible with gnuplot >=4.2
# author: Anna Schneider
# pale green - pale purple - pale orange - pale yellow - blue - magenta - brown - grey
# palette
set palette maxcolors 8
set palette defined (
0 '#7FC97F',\
1 '#BEAED4',\
2 '#FDC086',\
3 '#FFFF99',\
4 '#386CB0',\
5 '#F0027F',\
6 '#BF5B17',\
7 '#666666' )
</source>

Zbiory palet:
* [https://github.com/Gnuplotting/gnuplot-palettes github Gnuplotting : gnuplot-palettes]


Sprawdzamy jaki gradient ma aktualna paleta:

show palette gradient

Otrzymujemy:


0. gray=0.0000, (r,g,b)=(1.0000,1.0000,1.0000), #ffffff = 255 255 255
1. gray=1.0000, (r,g,b)=(0.0000,0.0000,0.0000), #000000 = 0 0 0

===test===
<source lang=c>
// command.c
/*
* process the 'test palette' command
* 1) Write a sequence of plot commands + set commands into a temp file
* 2) Create a datablock with palette values
* 3) Load the temp file to plot from the datablock
* The set commands then act to restore the initial state
*/
static void
test_palette_subcommand()
{
enum {test_palette_colors = 256};
struct udvt_entry *datablock;
char *save_replot_line;
TBOOLEAN save_is_3d_plot;
int i;

static const char pre1[] = "\
reset;\
uns border; se tics scale 0;\
se cbtic 0,0.1,1 mirr format '' scale 1;\
se xr[0:1];se yr[0:1];se zr[0:1];se cbr[0:1];\
set colorbox hor user orig 0.05,0.02 size 0.925,0.12;";

static const char pre2[] = "\
se lmarg scre 0.05;se rmarg scre 0.975; se bmarg scre 0.22; se tmarg scre 0.86;\
se grid; se xtics 0,0.1;se ytics 0,0.1;\
se key top right at scre 0.975,0.975 horizontal \
title 'R,G,B profiles of the current color palette';";

static const char pre3[] = "\
p NaN lc palette notit,\
$PALETTE u 1:2 t 'red' w l lt 1 lc rgb 'red',\
'' u 1:3 t 'green' w l lt 1 lc rgb 'green',\
'' u 1:4 t 'blue' w l lt 1 lc rgb 'blue',\
'' u 1:5 t 'NTSC' w l lt 1 lc rgb 'black'\
\n";

FILE *f = tmpfile();

#if defined(_MSC_VER) || defined(__MINGW32__)
/* On Vista/Windows 7 tmpfile() fails. */
if (!f) {
char buf[PATH_MAX];
/* We really want the "ANSI" version */
GetTempPathA(sizeof(buf), buf);
strcat(buf, "gnuplot-pal.tmp");
f = fopen(buf, "w+");
}
#endif

while (!END_OF_COMMAND)
c_token++;
if (!f)
int_error(NO_CARET, "cannot write temporary file");

/* Store R/G/B/Int curves in a datablock */
datablock = add_udv_by_name("$PALETTE");
if (datablock->udv_value.type != NOTDEFINED)
gpfree_datablock(&datablock->udv_value);
datablock->udv_value.type = DATABLOCK;
datablock->udv_value.v.data_array = NULL;

/* Part of the purpose for writing these values into a datablock */
/* is so that the user can read them back if desired. But data */
/* will be read back using the current numeric locale, so for */
/* consistency we must also use the locale when creating it. */
set_numeric_locale();
for (i = 0; i < test_palette_colors; i++) {
char dataline[64];
rgb_color rgb;
double ntsc;
double z = (double)i / (test_palette_colors - 1);
double gray = (sm_palette.positive == SMPAL_NEGATIVE) ? 1. - z : z;
rgb1_from_gray(gray, &rgb);
ntsc = 0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b;
sprintf(dataline, "%0.4f %0.4f %0.4f %0.4f %0.4f %c",
z, rgb.r, rgb.g, rgb.b, ntsc, '\0');
append_to_datablock(&datablock->udv_value, strdup(dataline));
}
reset_numeric_locale();

/* commands to setup the test palette plot */
enable_reset_palette = 0;
save_replot_line = gp_strdup(replot_line);
save_is_3d_plot = is_3d_plot;
fputs(pre1, f);
fputs(pre2, f);
fputs(pre3, f);

/* save current gnuplot 'set' status because of the tricky sets
* for our temporary testing plot.
*/
save_set(f);

/* execute all commands from the temporary file */
rewind(f);
load_file(f, NULL, 1); /* note: it does fclose(f) */

/* enable reset_palette() and restore replot line */
enable_reset_palette = 1;
free(replot_line);
replot_line = save_replot_line;
is_3d_plot = save_is_3d_plot;
}
</source>


=Rysowanie danych z pliku=
=Rysowanie danych z pliku=

Wersja z 19:58, 12 sty 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

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]

Kolor

Kolor [7]

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 , 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";

Rysowanie danych bez pliku

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


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)[9]

Przykład: [10]

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: [11]

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

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[12]

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[13]
  • tekst w pliku z danymi[14]

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. Wizualizacja danych - Gnuplot, dr hab. Bożena Woźna-SzczeŚniak
  8. Stackoverflow : Gnuplotting data without a textfile
  9. gnuplot documentation : page 68 = fit
  10. dopasowanie krzywej z Katedry Biotechnologii Środowiskowej UŚ
  11. stackoverflow question: fitting-a-curve-to-specific-data
  12. stackoverflow questions : gnuplot-nested-do-loop-and-plotting-on-the-same-graph
  13. stackoverflow question: gnuplot-bad-data-on-line-1
  14. ubuntu forums: ] Gnuplot and openoffice
Commons
Commons