colormap but with 2 values, one has positive and negative value (positive value = blue, negative value = red) and pvalue (the color graduates) in javascript in matlab

In Matlab, you can create a custom colormap using the colormap function. For your case, you can define a colormap that maps negative values to red and positive values to blue:

main.m
cmap = [linspace(1, 0, 100)', zeros(100, 1), linspace(0, 1, 100)'; % red to blue
        linspace(0, 1, 100)', zeros(100, 1), linspace(1, 0, 100)']; % blue to red
163 chars
3 lines

This creates a 200x3 matrix cmap, where each row corresponds to a color. The first 100 rows are red-to-blue colors, and the second 100 rows are blue-to-red colors. For example, the first row is [1 0 0] (pure red), and the last row is [0 0 1] (pure blue).

To use this colormap in JavaScript, you can convert the cmap matrix into an array of RGB strings using the rgb2hex function (which is included in some JavaScript libraries like Chroma.js). Here's an example:

index.tsx
// Define the colormap as a 200x3 matrix
var cmap = [
    [1, 0, 0],
    [0.99, 0.01, 0],
    // (more colors omitted for brevity)
    [0, 0, 1],
    [0.01, 0, 0.99]
];

// Convert the colormap to an array of hex strings
var colors = cmap.map(function(rgb) {
    var r = Math.floor(rgb[0] * 255);
    var g = Math.floor(rgb[1] * 255);
    var b = Math.floor(rgb[2] * 255);
    return '#' + r.toString(16) + g.toString(16) + b.toString(16);
});

// Use the colormap to color your data (here, "data" is an array of values)
var colorScale = chroma.scale(colors).domain([-1, 1]); // create a color scale that maps -1 to red and 1 to blue
var colors = data.map(function(value) {
    return colorScale(value).hex();
});
714 chars
23 lines

This code creates a color scale that maps the range [-1, 1] to the red-to-blue colormap we defined earlier, and then uses the chroma.scale function to create a color scale object. The colors array is then populated by calling the color scale object with each value in the data array.

Note that this code requires the Chroma.js library, which you can download from https://vis4.net/chromajs/.

related categories

gistlibby LogSnag