Search code examples
javascriptgraphicsjsxgraph

How would one precisely adjust axis, ticks, and a grid using JSXGraph library?


What would be the best approach to creating the graph just like the one below using JSXGraph? For example, how would I make axis go beyond the grid, etc.?

enter image description here

Have looked at the official documentation and external guides. Could not find information on how to adjust the ticks, grid, and axis so that I can generate the included graph.


Solution

  • Indeed, axis configuration is sort of complicated in JSXGraph. First, I would not recommend to use the deprecated grid, since it does not have tick labels. For configuration of default axes, JSXGraph has the attribute defaultAxes.

    The horizontal axis can be accessed by the sub-attribute x, the vertical axis by y.

    Now, we do the following to imitate the above image:

    1. Turn off automatic tick positioning by insertTicks: false
    2. The x-axis has labels at every other tick line: minorTicks: 1
    3. The y-axis has labels at every tick line: minorTicks: 0
    4. Both axes have labels for 2, -2, 4, -4, 6, ...: ticksDistance: 2
    5. If the automatic tick positioning is turned off, there will appear performance problems if users zoom out. Therefore, it might be advisable to limit the zoom factor: zoom: {min: 0.5, max: 2}
    6. The labels can be styled by supplying a CSS class: label: {fontSize: 16, display: 'html', cssClass: 'tickLabels'}

    Here is the complete example:

    const board = JXG.JSXGraph.initBoard('jxgbox', { 
        boundingbox: [-9, 17, 9, -17], axis:true,
        defaultAxes: {
            x: {
            ticks: {
              insertTicks: false, // Turn off automatic tick placing
              minorTicks: 1,      // One minor tick between two major ticks
              minorHeight: -1,    // Minor ticks are finitely long, too
              ticksDistance: 2,   // Major ticks are positioned at multiples of two
              label: {fontSize: 16, display: 'html', cssClass: 'tickLabels'}
            }
          },
            y: {
            ticks: {
              insertTicks: false, // Turn off automatic tick placing
              minorTicks: 0,      // No minor ticks between major ticks
              ticksDistance: 2,   // Major ticks are positioned at multiples of two
              label: {fontSize: 16, display: 'html', cssClass: 'tickLabels'}
            }
          }
        },
        zoom: {
          min: 0.5,
          max: 2
        }
    });
    
    .tickLabels {
      background-color: white;
      padding: 1px
    }
    

    See it live at https://jsfiddle.net/b684vfaL/2/.