pythongnuplotjupyter-lab

How can I add custom xtics for a python gnuplotlib plot?


I want to add custom tick labels on the x-axis using the python gnuplotlib.

I have tried (using jupyterlab):

import numpy as np
import gnuplotlib as gp

xtics_positions = [0, 2, 4, 6, 8]
xtics_labels = ["zero", "two", "four", "six", "eight"]
xtics = [(label, pos) for label, pos in zip(xtics_labels, xtics_positions)]

datapoints = np.array([ 0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0, 11,  5,  5,  2, 21,  1, 21,  0,  8, 62, 56,  0,  0,  0,  6,  3, 32,  7, 17,  1,  6, 10, 12,  0, 21, 11,  6, 14,  1, 15, 25, 30, 17, 11,  6,  4,  0])
gp.plot(datapoints, xtics = xtics)

but that does not work.

If I call gp.plot(datapoints), the plot produced is:

plot


Solution

  • First: when I run your code in console then I see error message

    gnuplotlib.GnuplotlibError: 
    Option 'xtics' not not known in any '['curve', 'subplot', 'process']' options sets
    

    I found that there is other module py-gnuplot which uses xtics=...
    but module gnuplotlib needs set=['xtics ...']

    gp.plot(..., set=['xtics ("five" 5,"ten" 10,"more" 30)'])
    

    enter image description here


    xtics_strings = [f'"{label}" {pos}' for label, pos in zip(xtics_labels, xtics_positions)]
    text = 'xtics (' + ','.join(xtics_strings) + ')'
    
    gp.plot(datapoints, set=[text])
    

    enter image description here

    Full code:

    import numpy as np
    import gnuplotlib as gp
    
    xtics_positions = [0, 2, 4, 6, 8]
    xtics_labels = ["zero", "two", "four", "six", "eight"]
    xtics = [(label, pos) for label, pos in zip(xtics_labels, xtics_positions)]
    
    datapoints = np.array([ 0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0, 11,  5,  5,  2, 21,  1, 21,  0,  8, 62, 56,  0,  0,  0,  6,  3, 32,  7, 17,  1,  6, 10, 12,  0, 21, 11,  6, 14,  1, 15, 25, 30, 17, 11,  6,  4,  0])
    
    #gp.plot(datapoints, set=['xtics ("five" 5,"ten" 10,"more" 30)']
    
    xtics_strings = [f'"{label}" {pos}' for label, pos in zip(xtics_labels, xtics_positions)]
    text = 'xtics (' + ','.join(xtics_strings) + ')'
    
    gp.plot(datapoints, set=[text])
    

    Custom xtics in gnuplot - Stack Overflow

    Gnuplotlib source code: set/unset

    Gnuplot doc: xtics (see | ({"<label>"} <pos> {<level>} {,{"<label>"}...) })