D3图表未显示浏览器



我已经下载了这个可视化:https://vizhub.com/Mithunprom/6f378ad23e3e4a2f99949368f02e3290

如果您访问该链接,您将能够看到所有源文件,包括它们的代码。

我无法在浏览器中通过index.html运行它,浏览器中没有显示任何内容。。我只是想让它发挥作用。

这是index.html:

<!DOCTYPE html>
<html>
<head>
<title>Making a Bar Chart</title>
<link rel="stylesheet" href="styles.css">
<script src="https://unpkg.com/d3@5.6.0/dist/d3.min.js"></script>
</head>
<body>
<svg width="960" height="500"></svg>
<script src="bundle.js"></script>
</body>
</html>

您需要从指定的URL添加脚本部分和css代码。我还做了完成任务所需的更改。

请找到下面的工作示例:

const data = [{
country: 'China',
population: 1415046
},
{
country: 'India',
population: 1354052
},
{
country: 'United States',
population: 326767
},
{
country: 'Indonesia',
population: 266795
},
{
country: 'Brazil',
population: 210868
},
{
country: 'Pakistan',
population: 200814
},
{
country: 'Nigeria',
population: 195875
},
{
country: 'Bangladesh',
population: 166368
},
{
country: 'Russia',
population: 143965
},
{
country: 'Mexico',
population: 130759
},
];
data.forEach(d => {
d.population = +d.population * 1000;
});
const titleText = 'Top 10 Most Populous Countries';
const xAxisLabelText = 'Population';
const svg = d3.select('svg');
const width = +svg.attr('width');
const height = +svg.attr('height');
const render = data => {
const xValue = d => d['population'];
const yValue = d => d.country;
const margin = {
top: 50,
right: 40,
bottom: 77,
left: 180
};
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
const xScale = d3.scaleLinear()
.domain([0, d3.max(data, xValue)])
.range([0, innerWidth]);
const yScale = d3.scaleBand()
.domain(data.map(yValue))
.range([0, innerHeight])
.padding(0.1);
const g = svg.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`);
const xAxisTickFormat = number =>
d3.format('.3s')(number)
.replace('G', 'B');
const xAxis = d3.axisBottom(xScale)
.tickFormat(xAxisTickFormat)
.tickSize(-innerHeight);
g.append('g')
.call(d3.axisLeft(yScale))
.selectAll('.domain, .tick line')
.remove();
const xAxisG = g.append('g').call(xAxis)
.attr('transform', `translate(0,${innerHeight})`);
xAxisG.select('.domain').remove();
xAxisG.append('text')
.attr('class', 'axis-label')
.attr('y', 65)
.attr('x', innerWidth / 2)
.attr('fill', 'black')
.text(xAxisLabelText);
g.selectAll('rect').data(data)
.enter().append('rect')
.attr('y', d => yScale(yValue(d)))
.attr('width', d => xScale(xValue(d)))
.attr('height', yScale.bandwidth());
g.append('text')
.attr('class', 'title')
.attr('y', -10)
.text(titleText);
};
render(data);
body {
margin: 0px;
overflow: hidden;
}
rect {
fill: steelblue;
}
<!DOCTYPE html>
<html>
<head>
<title>Making a Bar Chart</title>
<link rel="stylesheet" href="styles.css">
<script src="https://unpkg.com/d3@5.6.0/dist/d3.min.js"></script>
</head>
<body>
<svg width="960" height="500"></svg>
<script src="bundle.js"></script>
</body>
</html>

最新更新