【问题标题】:Adding Glyph based on condition in line graph in d3根据d3中折线图中的条件添加字形
【发布时间】:2017-10-30 22:26:58
【问题描述】:

This is the output that I would be requiring

This is the output that I am getting at the moment

我已经在我的 d3 代码中添加了圆形字形,但我需要根据条件添加字形,如果月份是一月,那么只有圆圈才会出现!例如,按照 01/2019、01/2020、01/2021 的顺序,圆圈应仅出现在这些日期

g.selectAll("circle") .data(dataIS) .enter() .append("circle") .attr("cx", function (d) { return x(parseTime(d.date));}) .attr("cy", function (d) { return y(d.salary + d.bonus); }) .attr("r", "4") .style("stroke","black") .style("stroke-width","2") .style("fill", "red" );

这会在所有日期创建圈子,我需要过滤并仅在 1 月显示它们

【问题讨论】:

  • 你能添加一个代码示例吗?
  • 欢迎来到 StackOverflow。请使用代码编辑您的问题(有一个“编辑”按钮),而不是在 cmets 中编写代码。另外,请添加所有相关代码(minimal reproducible example)以获得正确答案。
  • @MiroslavLigas - 已添加代码,感谢您的帮助!

标签: javascript html d3.js data-visualization linechart


【解决方案1】:

您能否过滤数据并仅在数据中月份为一月时添加圆圈?

我假设dataIS 是某种数组。

g.selectAll("circle")
.data(
  dataIS
  .filter(
    d =>{
      console.log("d is:",JSON.stringify(d,undefined,2));
      return d.date.getMonth() === 0 //only January
    }
  )
)
.enter()
...

【讨论】:

  • @HMR g.selectAll("circle") .data( dataIS .filter( d => d.date.getMonth() === 0 //仅 1 月 ) ) .enter() 。 append("circle") .attr("cx", function (d) { return x(parseTime(d.date)); }) .attr("cy", function (d) { return y(d.salary + d.bonus); }) .attr("r", "4") .style("stroke","black") .style("stroke-width","2") .style("fill","深红”);我已经添加了你给出的代码,但是在运行它时,轴和圆圈消失了
  • @jeet08 是否可以按 F12(最好在 Chrome 中)并在开发人员工具的控制台选项卡中查看是否有异常。我的猜测是getMonth is not a function 因为d.date 要么未定义要么不是日期对象。您可以在 getMonth(更新的答案)之前 console.log(JSON.stringify(d,undefined,2)) 并使用输出更新您的问题。
  • 我也尝试运行编辑后的代码,但它不会产生输出
  • @jeet08 如果它不产生输出,它一定会产生错误,或者dataIS 是一个空数组。您在最近的 Chrome 中尝试过吗?代码在 ES2015 中,也许你在不支持它的浏览器中尝试它,所以会出现错误。您可以使用 babel 对其进行转译或使用较旧的语法(d=>...function(d)... 相同
  • 运行您提供的代码时,整个图表消失或没有变化,我每个月都会出现圆圈!我没有收到这样的错误
猜你喜欢
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 2018-05-09
  • 1970-01-01
相关资源
最近更新 更多