The radial gradient in d3.js does not properly affect paths

My goal is to create a radial gradient on my path element, but for some reason the radial gradient does not apply correctly. Can anyone help me troubleshoot this issue?

Below is my updated code:

// Define the canvas / graph dimensions
var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;

var svg = d3.select("body")
    .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
    .append("g")
        .attr("transform", 
              "translate(" + margin.left + "," + margin.top + ")");

// Set the scales
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

svg.append("linearGradient")                
        .attr("id", "line-gradient")            
        .attr("gradientUnits", "userSpaceOnUse")    
        .attr("x1", 0).attr("y1", y(0))         
        .attr("x2", 0).attr("y2", y(1000))      
    .selectAll("stop")                      
        .data([                             
            {offset: "0%", color: "red"},       
            {offset: "40%", color: "black"},        
            {offset: "62%", color: "black"},        
            {offset: "62%", color: "lawngreen"},    
            {offset: "100%", color: "lawngreen"}    
        ])                  
    .enter().append("stop")         
        .attr("offset", function(d) { return d.offset; })   
        .attr("stop-color", function(d) { return d.color; });

// Draw the valueline path.
svg.append("path")
    .attr("class", "line")
    .attr("d", "M1,5L400,60");

View jsfiddle example here

Answer №1

After reviewing your code, I noticed an issue with how you defined attributes for the linear gradient. The following lines were unclear to me:

.attr("x1", 0).attr("y1", y(0))         
.attr("x2", 0).attr("y2", y(55))   

Therefore, I made some adjustments:

.attr("x1", 0).attr("y1", 0)            
.attr("x2", 100).attr("y2", 55)  

These coordinates determine how the gradient will flow along the X and Y axes, from point (x1,y1) of the target element to which the gradient is applied, to point (x2,y2). D3 did not recognize y(0) and y(1000) coordinates, resulting in the gradient not being applied correctly to the path.

In addition, I removed one of color offsets, and it seems to be working now.

You can find the updated JSFiddle link here

I hope this explanation helps clarify things for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to substitute the <mark> element within a string with the text enclosed in the tag using JavaScript

In need of help with replacing tags inside a string using JavaScript. I want to remove the start and end tags, while keeping the content intact. For example, if my input string is: <div class="active"><mark class="active-search-position">The ...

What is the method for ensuring a p element is only as wide as necessary when it wraps within a parent div with a specified hardcoded width?

Is there a way to adjust the width of the p-element in my example below based on the text inside without affecting the normal line break behavior, using only CSS if possible? It appears to be ignoring wrapping and is too wide: https://i.stack.imgur.com ...

Creating a bezel design in CSS or Vue: A step-by-step guide

Embedding: Is there a CSS property that can be used to create the same angle as shown in the layout? I looked everywhere in the program but couldn't find this specific property. Tried searching here !: ...

Is it possible to use Javascript to retrieve a variable from a remote PHP file?

I am trying to retrieve a variable from a remote PHP file using JavaScript in my phonegap application. The same origin policy doesn't apply here, so I believe I need to use JSON/AJAX for this task. However, I have been unable to find any tutorials tha ...

Why does this inner HTML table always adjust its width based on the content within it? Is there a way to make it match the width of its container instead

I'm not very familiar with HTML and CSS, and I've come across a problem. Here is the CSS structure in question: <!-- TECHNICAL REFERENCE: --> <div id="referenteTecnicoTab"> <table width="800px" class="standard-table-cls table-he ...

I'm encountering an unfamiliar error within my Discord.js bot, and I'm unsure of both its cause and the appropriate solution. Additionally, I'm unsure which specific file

I'm facing a recurring issue with my bot terminal. It's been causing me trouble for the past four days, functioning intermittently without any pattern. I'm struggling to track down the specific file where this error is originating from. Any ...

Running multiple instances of setTimeout() in JQuery

I'm looking for a way to delay the execution of 10 lines of independent jQuery code with 2 seconds between each line. I initially tried using setTimeout() on each line, but is there a more elegant solution for this scenario? The jQuery DELAY method do ...

Disabling the @import cache feature in LessCSS Assetic

I'm facing a minor issue that is robbing me of precious time. Currently, I am using the assetic plugin with the lesscss filter in my symfony2.1 project. The problem lies in Assetic not detecting changes in imported files when using the @import functi ...

Discover the absent style attributes within an HTML code in C# and incorporate them

Currently facing a challenging situation where I have a C# string with html tags: string strHTML = "<span style="font-size: 10px;">Hi This is just a section of html text.</span><span style="font-family: 'Verdana'; font-size: 10px; ...

CSS: Troubles with Element Widths

I'm dealing with a list item that contains an image, like so: <ul> <li> <img></img> </li> </ul> The image is not filling the entire width of the list item. Is there a way to make the list item shr ...

Material-UI Autocomplete can only save and display one specific property of an object at a time

Can someone help me with implementing Autocomplete from Material-UI? I want to store only a specific property value and not the entire object. For example, let's say I want to store the property Value, but it could be any other property as well. con ...

What is the best way to implement a custom NgbDateParserFormatter from angular-bootstrap in Angular 8?

Currently, I am working on customizing the appearance of dates in a form using Angular-Bootstrap's datepicker with NgbDateParserFormatter. The details can be found at here. My goal is to display the date in the format of year-month-day in the form fi ...

Display a portion of the existing URL as a clickable link on the webpage using JavaScript or PHP

If I have a website with the URL and I would like to showcase the image at https://example.com/image.jpg on my site (), what can I do? I attempted the following approach, but it only displays the URL of the image. <p id="image"></p> <scri ...

Restrict access to table records by specifying an array of row identifiers

Hi everyone, I've encountered a small issue. Just to provide some background, I have a table with checkboxes. Each row in the table has an associated ID, and when selected, I receive an array like this: const mySelectedRoles = [1997, 1998, 1999] Once ...

CSS selector for the only child element without any other adjacent sibling elements that are non-space characters

Here is a snippet of my code: <!DOCTYPE html> <html> <head> <style> code { display: inline-block; padding: 0; color: red; } p > code:only-child { display: block; white-space: pre; padding: 20px; line-height: 125 ...

Tips for utilizing JavaScript getElementByClassName to retrieve all the elements within a ul without having to specify the class name in each li

Looking to tidy up my HTML/CSS. Is there a way to keep this JavaScript functioning without needing to add the class name to every li element within the ul? Any suggestions on how to improve the visual appeal and readability of the HTML code? const Profi ...

The code provided creates a web form using HTML and ExpressJS to store submitted information into a MongoDB database. However, there seems to be an issue with the 'post' method, while the 'get' method functions correctly

When I try to submit entries (name, email, address) on localhost:3000 in the browser, the 'post' function is not creating an object in the mongo database even though it works from the postman. The browser displays an error message saying "unable ...

Fluid Centered UL with Bullet Points

We have received a unique request from one of our clients. They are asking for the content within a specific <ul> to be centered along with the icons. Centering and adding icons are doable, but the challenge lies in centering the <li> elements ...

Different scenarios call for different techniques when it comes to matching text between special characters

I encounter different scenarios where strings are involved. The goal is to extract the text in between the || symbols. If there is only one ||, then the first part should be taken. For example: Useless information|| basic information|| advanced informa ...

Loop through a list of form names using ng-repeat and send each form name to a JavaScript function when clicked

I have multiple forms within an ng-repeat loop, each with a different name. I need to pass the form data when a button inside the form is clicked. However, when I try to call it like this: checkSaveDisable(updateProductSale_{{productIndex}}) it thro ...