D3 多折线图

如何解决D3 多折线图

这是我必须在 D3 折线图上绘制的数据,其中的线是 AddonLossNew重复。图例中应显示相同的内容:

dataf: [
        {
          drugs: "BENEPALI",Addon: 328,Loss: 560,New: 250,Repeat: 321,},{
          drugs: "CIMZIA",Loss: 460,{
          drugs: "COSENTYX",Addon: 265,Loss: 360,Repeat: 421,{
          drugs: "ENBREL",Addon: 281,Loss: 260,New: 150,{
          drugs: "TALTZ",Addon: 290,],

我在绘制图例和绘图轴方面取得了一些成功,但没有使用线条。我认为数据有问题。

代码如下:

<template>
  <div>
    <b-button @click="esCall(dataf,stacklist,1460,350)">es call</b-button>
    <div id="kmCurveLegend" style="margin-left: -150px; margin-top: 30px"></div>
    <div id="kmCurve" style="margin-top: 10px"></div>
  </div>
</template>
<script>
import * as d3 from "d3";
import d3Tip from "d3-tip";
export default {
  data() {
    return {
      dataf: [
        {
          drugs: "BENEPALI",stacklist: ["Addon","Loss","New","Repeat"],xlabel: [],sumstat: null,mktSegName: "",current_stacks: null,height: 0,width: 0,svg: null,res: null,x1: null,minWidth: null,minHeight: null,stacks: null,totalStacks: null,data: null,};
  },mounted() {
    // this.kmLayout();
  },methods: {
    esCall(dataf,w,h) {
      this.stacks = stacklist;
      this.data = dataf;
      this.minWidth = w;
      this.minHeight = h;
      this.kmLayout(this.minWidth,this.minHeight,this.data,this.stacks);
    },kmLayout(w,h,data,stacklist) {
      d3.selectAll("#KMGraph").remove();
      // set the dimensions and margins of the graph
      var margin = { top: 10,right: 30,bottom: 30,left: 60 };
      this.width = w - margin.left - margin.right;
      this.height = h - margin.top - margin.bottom;

      // append the svg object to the body of the page
      this.svg = d3
        .select("#kmCurve")
        .append("svg")
        .attr("id","KMGraph")
        .attr("width",this.width + margin.left + margin.right)
        .attr("height",this.height + margin.top + margin.bottom)
        .append("g")
        .attr("transform","translate(" + margin.left + "," + margin.top + ")");

     
      //Grouping according to multiple MS

      var updatedData = [];
      for (var i in data) {
        updatedData.push(data[i]);
      }
      this.sumstat = d3.group(
        updatedData,(d) => d.Addon && d.Loss && d.New && d.Repeat
      );
      console.log("this.sumstat",this.sumstat);
  

      var x = d3
        .scaleBand()
        .domain(
          data.map(function (d) {
            return d.drugs;
          })
        )
        .range([0,this.width]); // This controls the Horizontal position of the Axis

      // Draw the axis
      this.svg
        .append("g")
        .attr("transform","translate(0," + this.height + ")") // This controls the vertical position of the Axis
        .call(d3.axisBottom(x));

      // Add Y axis
      var y = d3
        .scaleLinear()
        .domain([
          0,d3.max(data,function (d) {
            return +d.Loss + d.Addon + d.New + d.Repeat;
          }),])
        .range([this.height,0]);
      this.svg.append("g").call(d3.axisLeft(y));

      //tooltip
      this.tip = d3Tip()
        .attr("class","d3-tip")
        .direction("e")
        .html(function (d,i) {
          return (
            "<div style='margin-top:20%;background-color:whitesmoke;border-radius:4px;color:black;padding:5px'><strong>" +
            i[0]
            // +
            // "</strong><br><strong>(  " +
            // i[1][parseInt(r / 10)] +
            // "," +
            // i[1][parseInt(r / 10)].sum +
            // ")</strong></div>"
          );
        });

      this.svg.call(this.tip);
      var dataArray = Array.from(this.sumstat,([key,value]) => ({
        key,value,}));

      var color = d3
        .scaleOrdinal()
        .domain(
          stacklist.map(function (d) {
            return d;
          })
        )
        .range([
          "#e20000","#377eb8","#4daf4a","#250056 ","#ff9300","#df216d","#a65628","#0768fd","#00c221","#9e54b0","#ffff33","#10558a","#595959",]);
      this.svg
        .selectAll(".line")
        .data(this.sumstat)
        .enter()
        .append("path")
        .attr("class","lineKM")
        .attr("id",(d) => "kmCurve" + d[1])
        .attr("fill","none")
        .attr("stroke",function (d) {
          console.log(d);
          console.log("color",d[0],color(d[0]));
          return color(d[0]);
        })
        .attr("stroke-width",3.5)
        .attr("d",function (d) {
          return d3
            .line()
            .x((d) => {
              console.log("5555555555555555555555",x(d.drugs));
              return x(d.drugs);
            })
            .y((d) => {
              console.log("66666666666666666666666",y(d.Addon));
              return y(d.Addon);
            })(
            d[1].sort(function (a,b) {
              console.log("bbbbbbbbbbbbbbbbbbb",b.Addon - a.Addon);
              return b.Addon - a.Addon;
            })
          );
    
        })
        .on("mouseover",function (d) {
          d3.selectAll("#kmCurve" + d.replace(/[^a-zA-Z0-9]/g,"_")).style(
            "opacity",0.1
          );
          d3.select(this).style("opacity",1);
        })
        .call(this.tip)
        .on("mouseover",this.tip.show)
        .on("mouseout",this.tip.hide);
        this.svg
        .selectAll(".line")
        .data(this.sumstat)
        .enter()
        .append("path")
        .attr("class",y(d.Loss));
              return y(d.Loss);
            })(
            d[1].sort(function (a,b.Loss - a.Loss);
              return b.Loss - a.Loss;
            })
          );
          

        })
        
        .on("mouseover",this.tip.hide);

this.svg
        .selectAll(".line")
        .data(this.sumstat)
        .enter()
        .append("path")
        .attr("class",y(d.New));
              return y(d.New);
            })(
            d[1].sort(function (a,b.New - a.New);
              return b.New - a.New;
            })
          );
         
        })
        
        .on("mouseover",y(d.Repeat));
              return y(d.Repeat);
            })(
            d[1].sort(function (a,b.Repeat - a.Repeat);
              return b.Repeat - a.Repeat;
            })
          );
       
        })
        
        .on("mouseover",this.tip.hide);

       this.createLegend(stacklist);
    },createLegend(stacklist) {
      d3.selectAll("#KmLegends").remove();
  
      var stacks = stacklist;
      this.current_stacks = stacks;
      console.log("stacks",stacks);
      this.stackedZ = d3
        .scaleOrdinal()
        .range([
          "#e20000",])
        .domain(stacks);
      this.legendsvg = d3
        .select("#kmCurveLegend")
        .append("svg")
        .attr("class","legendKmCurve")
        .attr("id","KmLegends")
        .attr("width",1000)
        .attr("height",50);
      this.legendg = this.legendsvg.append("g");
      stacks.forEach((d,i) => {
        var position = i;
        this.legendg
          .append("circle")
          .attr("class","legendCircle")
          .attr("id","legendCircle" + d.replace(/[^a-zA-Z0-9]/g,"_"))
          .attr("r",10)
          .attr("cy",20)
          .attr("cx",position * 165 + 225)
          .attr("fill",this.stackedZ(d))
          .on("click",() => {
            this.addOrDelete(d);
          })
          .on("mouseover",() => {
            console.log("circle d",d);
            d3.selectAll(".lineKM").style("opacity",0.2);
            d3.select("#kmCurve" + d.replace(/[^a-zA-Z0-9]/g,"_")).style(
              "opacity",2
            );
            d3.selectAll(".legendCircle").style("opacity",0.1);
            d3.select("#legendCircle" + d.replace(/[^a-zA-Z0-9]/g,2
            );
          })
          .on("mouseout",() => {
            d3.selectAll(".lineKM").style("opacity",1);
            d3.selectAll(".legendCircle").style("opacity",1);
          })
          .append("svg:title")
          .text(d);

        this.legendg
          .append("text")
          .attr("class","legendKM" + d.replace(/[^a-zA-Z0-9]/g,"_"))
          .on("click",(d,i,key) => {
            console.log("key of text",key);
            if (
              document.getElementById(
                "kmCurve" + d[0].replace(/[^a-zA-Z0-9]/g,"_").innerHTML
              ).style.opacity == 1
            ) {
              d3.selectAll(
                "#kmCurve" + d[0].replace(/[^a-zA-Z0-9]/g,"_").innerHTML
              ).style("opacity",0);
              d3.selectAll(
                "." + "legendKM" + d[0].replace(/[^a-zA-Z0-9]/g,"_").innerHTML
              )
                .style("text-decoration","line-through")
                .style("opacity",0.2);
              d3.selectAll(
                "#legendCircle" + d[0].replace(/[^a-zA-Z0-9]/g,0.2);
              this.$forceUpdate();
            } else {
              d3.selectAll(
                "#kmCurve" + d[0].replace(/[^a-zA-Z0-9]/g,1);
              d3.selectAll(
                "." + "legendKM" + d[0].replace(/[^a-zA-Z0-9]/g,"none")
                .style("opacity",1)
                .style("white-space","nowrap")
                .style("text-overflow","ellipsis");
              d3.selectAll(
                "#legendCircle" + d[0].replace(/[^a-zA-Z0-9]/g,1);
              this.$forceUpdate();
            }
            this.$forceUpdate();

            this.addOrDelete(d[0].innerHTML);
          })
          .text(d)
          .attr("y",20)
          .attr("x",position * 165 + 240)
          .style("font-weight","bold")
          .style("font-size","18px")
          .attr("transform",6)")
          .append("svg:title");
        this.$forceUpdate();
      });
    },addOrDelete(name) {
      this.current_stacks.includes(name)
        ? this.filterData(name)
        : this.addData(name);
    },filterData(name) {
      console.log("this.current_stacks.length",this.current_stacks.length);
      if (this.current_stacks.length == 1) {
        return;
      }
      this.current_stacks = this.current_stacks.filter((obj) => {
        return obj != name;
      });
      this.kmUpdatedLayout(
        this.minWidth,this.current_stacks
      );
      this.legendUpdate(name,0);
    },addData(name) {
      if (this.current_stacks.includes(name)) {
        return;
      }
      this.current_stacks.push(name);
      this.kmUpdatedLayout(
        this.minWidth,1);
    },legendUpdate(name,status) {
      status
        ? d3
            .selectAll("." + "legendKM" + name.replace(/[^a-zA-Z0-9]/g,"_"))
            .style("text-decoration","none")
            .style("opacity",1)
        : d3
            .selectAll("." + "legendKM" + name.replace(/[^a-zA-Z0-9]/g,"line-through")
            .style("opacity",0.4);
    },};
</script>
<style scoped>
</style>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res