javascript - 无法将数据带入 D3 等值线图
问题描述
我在将约翰霍普金斯冠状病毒数据整合到 D3 choropleth 时遇到了麻烦,我很新,所以可能缺少一个基本的东西。该代码主要用于我在互联网上找到的各种资源,但这主要是一个自学 D3 的学习项目,因此将不胜感激。
获取数据的R代码:
library(tidyverse)
library(tools)
dat <- read.csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv")
states <- dat %>%
filter(Country.Region == "US",
!grepl(",",Province.State),
!grepl("Princess",Province.State),
Province.State != "District of Columbia") %>%
pivot_longer(5:ncol(.), names_to = "Date", values_to = "Cases") %>%
mutate(Date = str_remove(Date,"X"),
Date = as.Date(Date, "%m.%d.%y")) %>%
filter(Date == max(Date)) %>%
select(state = Province.State,
cases = Cases)
counties <- dat %>%
filter(Country.Region == "US",
grepl(",",Province.State),
!grepl("Princess",Province.State),
Province.State != "Washington, D.C.") %>%
separate(Province.State, c("county", "state"), ", ") %>%
mutate(county = str_remove(county, " County")) %>%
pivot_longer(6:ncol(.), names_to = "Date", values_to = "Cases") %>%
mutate(Date = str_remove(Date,"X"),
Date = as.Date(Date, "%m.%d.%y")) %>%
filter(Date == max(Date)) %>%
select(county = county,
state,
cases = Cases)
#write.csv(states, "state_cases.csv",row.names=FALSE)
#write.csv(counties, "county_cases.csv",row.names=FALSE)
#FIPS=====================================================================+++++
#county_fips <- read.csv("https://raw.githubusercontent.com/kjhealy/fips-codes/master/state_and_county_fips_master.csv") %>%
# select(id = fips,
# name,
# state) %>%
# mutate(id = str_pad(as.character(id), 5, pad = "0"),
# name = str_remove(name, " County"),
# name = toTitleCase(tolower(as.character(name))),
# id = case_when(grepl("000", id) ~ str_sub(id, end=-4),
# TRUE ~ id))
#
#write.csv(county_fips, "county_fips.csv",row.names=FALSE)
county_fips <- read.csv("county_fips.csv")
cases <- county_fips %>% filter(is.na(state)) %>%
left_join(states, by= c("name" = "state")) %>%
select(-state) %>%
rbind(
county_fips %>% filter(!is.na(state)) %>%
left_join(counties, by= c("name" = "county","state" = "state")) %>%
select(-state)
)
write.csv(cases, "cases.csv",row.names=FALSE)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coronavirus Cases</title>
<style>
.background {
fill: none;
pointer-events: all;
}
#states {
fill: none;
}
#states .active {
display:none;
}
#state-borders {
fill: none;
stroke: #fff;
stroke-width: 1px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;
}
.county-boundary {
fill: 'grey';
stroke: #fff;
stroke-width: .5px;
}
.county-boundary:hover, .state:hover {
fill: rgba(121, 121, 121, 0.2);
}
</style>
</head>
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<div class="viz"></div>
<script type="text/javascript">
var x = d3.scaleLinear()
.domain([1, 10])
.rangeRound([600, 860]);
var color = d3.scaleThreshold()
.domain(d3.range(0, 9))
.range(d3.schemeBlues[9]);
var margin = {
top: 10,
bottom: 10,
left: 10,
right:10
}, width = parseInt(d3.select('.viz').style('width'))
, width = width - margin.left - margin.right
, mapRatio = 0.5
, height = width * mapRatio
, active = d3.select(null);
var svg = d3.select('.viz').append('svg')
.attr('height', height + margin.top + margin.bottom)
.attr('width', width + margin.left + margin.right);
svg.append('rect')
.attr('class', 'background center-container')
.attr('height', height + margin.top + margin.bottom)
.attr('width', width + margin.left + margin.right)
.on('click', clicked);
var promises = [
d3.json("us-10m.v1.json"),
d3.csv("cases.csv", function(d) {
cases.set(d.id, +d.name +d.cases);
})
]
Promise.all(promises).then(ready)
var projection = d3.geoAlbersUsa()
.translate([width /2 , height / 2])
.scale(width);
var path = d3.geoPath()
.projection(projection);
var g = svg.append("g")
.attr('class', 'center-container center-items us-state')
.attr('transform', 'translate('+margin.left+','+margin.top+')')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
function ready(us) {
g.append("g")
.attr("id", "counties")
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.enter().append("path")
.attr("d", path)
.attr("fill", function(d) {
var sn = CountyNames.get(d.id)
d.rate = cases.get(countyNames.get(d.id)) || 0
var col = color(d.rate);
if (col) {
return col
} else {
return '#ffffff'
}
})
.attr("class", "county-boundary")
.on("click", reset);
g.append("g")
.attr("id", "states")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter().append("path")
.attr("d", path)
.attr("fill", function(d) {
var sn = StateNames.get(d.id)
d.rate = cases.get(stateNames.get(d.id)) || 0
var col = color(d.rate);
if (col) {
return col
} else {
return '#ffffff'
}
})
.attr("class", "state")
.on("click", clicked);
g.append("path")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("id", "state-borders")
.attr("d", path);
}
function clicked(d) {
if (d3.select('.background').node() === this) return reset();
if (active.node() === this) return reset();
active.classed("active", false);
active = d3.select(this).classed("active", true);
var bounds = path.bounds(d),
dx = bounds[1][0] - bounds[0][0],
dy = bounds[1][1] - bounds[0][1],
x = (bounds[0][0] + bounds[1][0]) / 2,
y = (bounds[0][1] + bounds[1][1]) / 2,
scale = .9 / Math.max(dx / width, dy / height),
translate = [width / 2 - scale * x, height / 2 - scale * y];
g.transition()
.duration(750)
.style("stroke-width", 1.5 / scale + "px")
.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
}
function reset() {
active.classed("active", false);
active = d3.select(null);
g.transition()
.delay(100)
.duration(750)
.style("stroke-width", "1.5px")
.attr('transform', 'translate('+margin.left+','+margin.top+')');
}
</script>
</body>
</html>
当我应该看到这些方面的东西时:http: //bl.ocks.org/ElefHead/ebff082d41ef8b9658059c408096f782
解决方案
推荐阅读
- ios - 使用自动布局快速添加阴影和仅左/右角半径
- c++ - 使用 Chemfiles 库读取轨迹文件时出错
- javascript - 防止 Ajax.Complete 中的循环
- windows - Heroku 推送在 Windows + Git bash 中失败
- ffmpeg - 我无法在带有淡入/淡出过渡的缩放和平移中设置视频持续时间
- java - 获取更新行的特定列
- javascript - 像帧缓冲区这样的画布在 chrome 上工作,但在 Firefox 上不工作
- python - 使用正则表达式提取并显示所有使用 Python 的接口的接口和方法状态
- android - 下载的图像显示在 android studio 但不是画廊
- powershell - 如何限制 ForEach 运行的次数