我在我的angular 6应用程序中有一个d3柱形图,我想在y轴上为y轴上的每个标签绘制线条。我希望这些行是这样的:
我不知道该如何画那些浅灰色的线!
这是我来自d3的代码:
createChart() {
const element = this.chartContainer.nativeElement;
this.width = element.offsetWidth - this.margin.left - this.margin.right;
this.height = element.offsetHeight - this.margin.top - this.margin.bottom;
const svg = d3.select(element).append('svg')
.attr('width', element.offsetWidth)
.attr('height', element.offsetHeight);
// chart plot area
this.chart = svg.append('g')
.attr('class', 'bars')
.attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);
// define X & Y domains
const xDomain = this.data.map(d => d[0]);
const yDomain = [10000, d3.max(this.data, d => d[1])];
// create scales
this.xScale = d3.scaleBand().padding(0.6).domain(xDomain).rangeRound([0, this.width]);
this.yScale = d3.scaleLinear().domain(yDomain).range([this.height, 0]);
// bar colors
this.colors = d3.scaleLinear().domain([0, this.data.length]).range(<any[]>['#00a0e9', '#00a0e9']);
// x & y axis
this.xAxis = svg.append('g')
.attr('class', 'axis axis-x')
.attr('transform', `translate(${this.margin.left}, ${this.margin.top + this.height})`)
.attr("stroke", "#777777")
.attr("stroke-width", 0.5)
.attr("fill", "none")
.call(d3.axisBottom(this.xScale));
this.yAxis = svg.append('g')
.attr('class', 'axis axis-y')
.attr('transform', `translate(${this.margin.left}, ${this.margin.top})`)
.attr("stroke", "#777777")
.attr("stroke-width", 0.5)
.attr("fill", "none")
.call(d3.axisLeft(this.yScale));
}
** 更新=>
我在y轴下方添加了新配置,它的工作原理有点好,但是线条的粗细不相等,另一个问题是我有120000和122000的值作为两个最大值y,但是图表绘制了两个都。它应该只能绘制120000
this.yAxis = svg.append('g')
.attr('class', 'axis axis-y')
.attr('transform', `translate(${this.margin.left}, ${this.margin.top})`)
.attr("stroke", "#777777")
.attr("stroke-width", 0.5)
.attr("fill", "none")
.call(d3.axisLeft(this.yScale));
svg.append("g")
.attr("class", "grid")
.attr('transform', `translate(${this.margin.left}, ${this.margin.top})`)
.attr("stroke-width", 0.1)
.attr("fill", "none")
.call(d3.axisLeft(this.yScale)
.tickSize(-this.width)
.tickFormat("")
);
答案 0 :(得分:1)
我曾经找到以下代码段:绘制第二个版本的y轴
g.append("g")
.attr("class", "grid")
.call(d3.axisLeft(y)
.tickSize(-width)
.tickFormat("")
);
您需要一些CSS来设置线条样式
.grid line {stroke: lightgrey;stroke-opacity: 0.7;shape-rendering: crispEdges;}
.grid path {stroke-width: 0;}
如果只需要网格线而不是轴,则可以使用axis.tickSizeInner([size])