0

I'm trying to append image urls to an SVG element using D3. I've tried various codes including this one.

svg.append('g')
.selectAll('image')
.data(data)
.enter()
.append('image')
.attr('class', 'countryflag')
.attr('href', `https://www.musiktrends.com/images/countryflags/`

+ 
data.map(yValues)
+
`.png`)

.attr('width', 50)
.attr('height', barHeight)
.attr('x', 0)
.attr('y', yPos)
.attr(`transform', `translate(5,`+0+`)`)
;

The problem with this code is that I get all countries in the url. I only want the country that corresponds to each value in the json array.

Here's the data array:

data = d3.json('data.json')
.then(data => {data
.forEach(d => {
d.country = d.country;
d.population = +d.population * 1000;
});
render(data);
});

I've tried writing a function as well but because I'm fairly new at this I couldn't figure it out. Thank you all in advance.

2 Answers 2

0

To build the flag URL, you're mapping the function yValues on the data array. Can you show what it is doing?

If you want an URL pre country, you should not use .map in the URL building but rather do a loop around the whole svg. ... call.

Also, note that on .attr(`transform', `translate(5,`+0+`)`), you're using different type of quotes around transform.

Sign up to request clarification or add additional context in comments.

Comments

0

Thank you Moutah. This is what I ended up doing and it seems to work fine:

Data:

data = d3.json('data.json')
.then(data => {data
.forEach(d => {
    d.country = d.country;
  d.population = +d.population * 1000;
  d.flagurl = `../images/countryflags/`+d.country+`.png`;
});

console.log(data);
render(data);
});

const yPos = d => yScale(yValues(d));

Image

svg.append('g')
.selectAll('image')
.data(data)
.enter()
.append('image')
.attr('class', 'countryflag')

.attr('href', d => (d.flagurl))

.attr('width', 50)
.attr('height', 0.8*barHeight)
.attr('x', 0)
.attr('y', yPos)
.attr('opacity', 0)
.attr('transform', `translate(`+0.05*barHeight+`,`+0.1*barHeight+`)`)

// transition and delay         
.transition()
//.attr ('y', yPos)
.attr ('opacity', 1)
//.attr('height', yScale.bandwidth())

.duration(animateDuration-625)
.delay(delay+animateDuration+375)
;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.