Tips for extracting the y-coordinate from a touch event using d3

I am utilizing d3.js to display data in my Ionic app. I have a touch event that allows me to move a line and retrieve the coordinates where it intersects with my chart. While I can easily obtain the x-coordinate representing the date, I am struggling to get the continuous y-coordinates. Currently, I can find discrete y-coordinates by looping through the data array but I need the values "in-between". Below is how I am attempting this (I trigger the function drawChart() when the View loads)

private drawChart() {

    let width = 900 - this.margin.left - this.margin.right;
    let height = 500 - this.margin.top - this.margin.bottom;

    /*
        Data is structured as: [{date: , value: }]
    */
    let data = this.data;

    let svg = d3.select("#chart")
    .append("svg")
    .attr("width", '100%')
    .attr("height", '100%')
    .attr('viewBox','0 0 900 500')
    .append("g")
    .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");

    let x = d3Scale.scaleTime().range([0, width]);
    let y = d3Scale.scaleLinear().range([height, 0]);
    x.domain(d3Array.extent(this.data, (d) => d.date ));
    y.domain(d3Array.extent(this.data, (d) => d.value ));

    svg.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate(0,"+ height + ")")
        .call(d3Axis.axisBottom(x));

    svg.append("g")
        .attr("class", "axis axis--y")
        .call(d3Axis.axisLeft(y));

    let line = d3Shape.line()
    .x((d) => x(d.date))
    .y((d) => y(d.value));

    let path = g.append("path")
        .datum(this.data)
        .attr("class", "line")
        .attr("d", line);

    let cursorLine = svg
        .append("line")
        .attr("stroke-width",3)
        .attr("stroke","black")
        .style("opacity", 0);

    svg.on("touchstart", touched);
    svg.on("touchmove", touched);

    function touched() {
        let d = d3.touches(this);
        svg
        .selectAll("line")
        .data(d)
        .style("opacity", 1);

        svg
        .selectAll("line")
        .attr("x1", (d) => d[0])
        .attr("x2", (d) => d[0])
        .attr("y1", 0)
        .attr("y2", height);

        let formatTime = d3.timeFormat("%Y-%m-%d");
        let dateVal = formatTime(xScale.invert(d[0][0])); 
        let val = 0;

        data.forEach(d => {
           if(formatTime(d.date) === dateVal) {
               val = d.value;
            }
        })
    }
}

If you have any suggestions on how I can attain the y-values continuously while sliding the cursor line, please share! Any help would be greatly appreciated.

Answer №1

Perhaps you could give this a shot

let d = d3.touches(this);

If you can retrieve the x coordinate using this method

let dateVal: string = formatTime(xScale.invert(d[0][0])); //x-coordinate of the cursor line

Can you obtain the y coordinate like this

let dateVal2: string_y = y.invert(d[0][1]); //y-coordinate of the cursor line

I believe d3.touches is similar to d3.mouse.event. Could you use console.log to see what information is stored in d and it should include the y coordinate

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the implementation of custom global declaration in the latest version of NextJS, version

Looking to implement custom global declaration in NextJS In my NextJS project, I've defined a global prototype for String as shown below utils.d.ts export {} declare global { interface String { /** * Returns string after removing all htm ...

What is the process for connecting a date/time form control?

My code seems to only be working for the 'title' element, while the 'docdatetime' control remains blank. Can anyone spot what I'm doing wrong? //template =================================================== <div class="form-grou ...

An unexpected error occurred while running ng lint in an Angular project

I've encountered an issue while trying to run ng lint on my Angular project. After migrating from TSLint to ESLint, I'm getting the following error message when running ng lint: An unhandled exception occurred: Invalid lint configuration. Nothing ...

Confirm the Keycloak token by checking it against two separate URLs

In my system, I have a setup based on Docker compose with back-end and front-end components. The back-end is developed using Python Flask and runs in multiple docker containers, while the front-end is coded in TypeScript with Angular. Communication between ...

reusable angular elements

I'm facing a situation where I have a search text box within an Angular component that is responsible for searching a list of names. To avoid code duplication across multiple pages, I am looking to refactor this into a reusable component. What would b ...

Unable to reference the namespace 'ThemeDefinition' as a valid type within Vuetify

Looking to develop a unique theme for Vuetify v3.0.0-alpha.10 and I'm working with my vuetify.ts plugin file. import "@mdi/font/css/materialdesignicons.css"; import "vuetify/lib/styles/main.sass"; import { createVuetify, ThemeDefinition } from "v ...

Prevent Click Event on Angular Mat-Button

One of the challenges I'm facing involves a column with buttons within a mat-table. These buttons need to be enabled or disabled based on a value, which is working as intended. However, a new issue arises when a user clicks on a disabled button, resul ...

Exploring the incorporation of interfaces into Vue.js/Typescript for variables. Tips?

I have an interface:   export interface TaskInterface{ name: string description1: string time: string } and a component import { TaskInterface } from '@/types/task.interface' data () { return { tasks: [ { name: 'Create ...

Performing bulk operations on all selected rows in a table using Angular 6

Within my Angular 6 web application, there is a table with checkboxes in each row. My goal is to be able to perform bulk actions on the selected rows, such as deleting them. One approach I considered was adding an isSelected boolean property to the data m ...

The process of inserting data into MongoDB using Mongoose with TypeScript

Recently, I encountered an issue while trying to insert data into a MongoDB database using a TypeScript code for a CRUD API. The problem arises when using the mongoose package specifically designed for MongoDB integration. import Transaction from 'mon ...

Storing information using the DateRangePicker feature from rsuite - a step-by-step guide

Currently, I am working on storing a date range into an array using DateRangePicker from rsuite. Although my application is functioning correctly, I am encountering some TypeScript errors. How can I resolve this issue? import { DateRangePicker } from " ...

Issues with Angular 2 loading properly on Internet Explorer 11

We are currently running an Asp.net MVC 5 web application integrated with Angular 2. The application functions smoothly on Chrome, Firefox, and Edge browsers, but encounters loading issues on IE 11, displaying the error illustrated in the image below: ht ...

Dev4: utilizing scaleOrdinal for color mapping and selection

I have developed a code that generates line graphs on an SVG canvas, however, I am facing difficulties in altering the colors as I defined using the d3.scaleOrdinal function. Despite defining 12 distinct colors, the output I am getting looks like this. Is ...

What causes an error during the compilation of an Angular package containing a singleton class?

I am currently in the process of creating an Angular library. Within this library, I have developed a singleton class to manage the same SignalR connection. Here is the code implementation: import * as signalR from '@microsoft/signalr'; export c ...

Enhancing TypeScript Modules

Recently, I encountered an issue with my observable extension. Everything was functioning perfectly until I updated to angular 6 and typescript 2.7.2. import { Observable } from 'rxjs/Observable'; import { BaseComponent } from './base-compo ...

Unable to pass a parameter through an Angular http.get request

I've encountered an issue where I am attempting to pass the page number and page size values to a web API, but for some reason, no parameters are being passed. I have thoroughly debugged the application in VS Code, and verified that the pagingModel ob ...

Transform data into JSON format using the stringify method

I am facing an issue with my TypeScript code where I need to retrieve specific information from a response. Specifically, I want to output the values of internalCompanyCode and timestamp. The Problem: An error is occurring due to an implicit 'any&apo ...

Avoiding infinite loops in JavaScript events

This particular issue involves functions specific to D3, but is not limited to D3. I have developed two D3 charts and implemented zoom functionality on both with the intention of synchronizing the zoom scale and position - so that when one chart is zoomed, ...

The CosmosClient's read() method will only return an object if both the ID and partition key value are provided

After setting up a CosmosDB instance and inserting a test object into the container products, with the partition key set to /price, I encountered an issue. The item added had the following properties: { "id": "1234", "name": "A DB product", "p ...

Using scrollIntoView() in combination with Angular Material's Mat-Menu-Item does not produce the desired result

I am facing an issue with angular material and scrollIntoView({ behavior: 'smooth', block: 'start' }). My goal is to click on a mat-menu-item, which is inside an item in a mat-table, and scroll to a specific HTML tag This is my target ...