Is it possible to utilize two distinct data sources for the primary chart and dataZoom feature within Apache ECharts?

Working with Apache ECharts requires using two different data sources: one for the main chart and the other for the dataZoom preview.

To reduce data sent to clients, I have decreased the resolution over longer time periods. However, when a user zooms in on a smaller time range, I want the main chart to display higher resolution.

Experiencing issues similar to those shown in this screenshot, I am seeking advice on how to utilize separate data sources for the main chart and dataZoom overview. Any suggestions?

The intention is for the dataZoom chart to always show the complete chart while the main plot loads and displays the selected area.

To better illustrate my issue, I have created this example.

Answer №1

A clever method I suggest is to utilize a helper xAxis that includes the properties type: 'category', show: false, and represent your time data in the data property. This enables you to implement a dataZoom on this axis, triggering the dataZoom event to retrieve new data.

Check out this example:

function generateDateRandomPairs() {
  const dateRandomPairs = [];

  const date = new Date();

  var j = 1;
  for (let i = 0; i < 10000; i++) {
    const number = j;
    if (i % 10 == 0) {
      j++;
    }
    dateRandomPairs.push([date.toISOString(), number]);
    date.setSeconds(date.getSeconds() + 60);
  }

  return dateRandomPairs;
}

// All data but with lower resolution
// Should be used in dataZoom
var allData = generateDateRandomPairs();

// Data with high resolution
// Would be loaded through Ajax in real world
var mainPlotData = allData.slice(50, 200);

option = {
  tooltip: {
    trigger: 'axis'
  },
  xAxis: [
    {
      type: 'time',
      name: 'Date'
    },
    {
      type: 'category',
      data: allData.map((point) => point[0]),
      show: false
    }
  ],
  yAxis: [
    {
      gridIndex: 0,
      type: 'value',
      name: 'Value',
    }
  ],
  series: [
    {
      name: 'High-Res Data',
      type: 'line',
      xAxisIndex: 0,
      yAxisIndex: 0,
      data: mainPlotData
    }
  ],
  dataZoom: [
    {
      type: 'slider',
      xAxisIndex: 1,
      endValue: 200,
      realtime: false
    }
  ]
};

myChart.on('dataZoom', function(params) {
  const startIndex = Math.round((params.start / 100) * allData.length);
  const endIndex = Math.round((params.end / 100) * allData.length);
  let resolution = Math.ceil((endIndex - startIndex) / 200);
  resolution = resolution === 0 ? 1 : resolution;
  const data = allData.slice(startIndex, endIndex).filter((x, i) => i % resolution === 0);
  myChart.setOption({series: [{data: data}]})
});

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

Combine and transform multiple hierarchical JSONs into a new format

I'm facing a challenge where I need to merge two JSON objects and convert them into a different format using TypeScript in a React project. Initially, I tried implementing this with a recursive function as well as a reducer, but unfortunately, it didn ...

What is the best way to prioritize items on a list in JavaScript?

Looking to organize your to-do list items by priority? In this task list, users can enter an item, select a priority level, and add it to the list. Here is an example HTML form: <input id="task" type="text"/> <select id="priority"> <o ...

What is the best way to monitor and react to individual changes in a form array within an Angular application?

constructor(private stockService: StockService, private fb: FormBuilder, public dialog: MatDialog, public snackBar: MatSnackBar, private supplierService: SupplierService, private productService: ProductService) { this.stockForm = this.fb.group ({ //fo ...

What is the process for generating a new type that includes the optional keys of another type but makes them mandatory?

Imagine having a type like this: type Properties = { name: string age?: number city?: string } If you only want to create a type with age and city as required fields, you can do it like this: type RequiredFields = RequiredOptional<Propertie ...

Activate a Bootstrap tab using turbolinks dynamically

After loading the page, I am attempting to open a Bootstrap 4 tab. It works when I refresh the page, but if I navigate within the site, it gives me a query selector empty error. This code is a port of the solution mentioned in this tutorial, as I am using ...

How to retrieve email input using SweetAlert2 in PHP?

Hello there! I'm curious about the most effective method for integrating PHP with Javascript. My goal is to execute some coding tasks once an email address has been entered. swal({ type: "success", title: "Congrats!", text: "Please enter your P ...

The regex pattern did not match the line of code in the Node.js script

I need help finding a regex pattern that can identify any line of code containing just one reference to a core module. Here is an example: const coreModuleMatches = /'^[var|const]{0,1}[a-z\$\_]{1,}=require([\'|"][assert|fs|path][ ...

Encountering an issue with accessing a property in Angular's TypeScript module

I encountered an issue while trying to access a property of a static array that I created in a TypeScript class. The error message I received is as follows: ERROR TypeError: Cannot read property 'forbiddenProjectNames' of undefined Below is th ...

Simple steps to correct the npm installation of the React list filter

I encountered an issue while trying to install react-list-filter using npm (npm install react-list-filter). The error messages displayed in my console are as follows: npm ERR! code ETARGET npm ERR! notarget No matching version found for <a href="/cdn-c ...

Warning: Angular.js encountered a max of 10 $digest() iterations while iterating through array slices. Operation aborted

JSbin: http://jsbin.com/oxugef/1/edit I am attempting to slice an array into smaller subarrays and iterate through them in order to create a table of divs that are evenly divided. Unfortunately, there seems to be an issue where I am unknowingly overwritin ...

Utilizing Animate Function in Framer Motion for Object Animation

I am currently experimenting with the Framer Motion library in an attempt to create interactive movement for objects when they are clicked. My goal is to be able to relocate a component to a specific destination regardless of its initial position. I'm ...

Create a circular modal for the design

I am interested in creating a modal that has a circular shape instead of the typical rectangle with rounded corners. This means it should appear as just a simple round container with the modal-body content in the center, without any modal-header or modal-f ...

Ways to identify and differentiate user clicks on various buttons

I have generated 3 different plan options from an array of objects retrieved from the backend. Depending on whether the plan is cheaper, the user's subscription, the corresponding button will display "downgrade", more expensive, the button will show ...

Utilizing AJAX requests to execute create, update, and delete actions all from one streamlined file instead of separating them into three distinct

In my JavaScript code, I am currently making XMLHttpRequests to separate PHP files for different functionalities in my app - like add.php, update.php, and delete.php. However, having three separate files feels repetitive. Is there a way to consolidate al ...

Implement a customized range slider for precise numeric input

A slider within me makes use of an input range with the following current numbers: 12, 24, 36, 48, 60 I now require the ability to accommodate: 24, 36, 48, 60, 120 <input type="range" data-id='slider1RangePicker' name="ran ...

Obtain an HTML element using JavaScript

What is the best method to access the top-left cell of a table using JavaScript from a specified URL? For instance, in this URL: https://www.w3schools.com/jsref/dom_obj_table.asp In the 'Table Object Methods' section, I am interested in retriev ...

Switching AngularJS templates without modifying the URL

Just diving into Angular and JS, so my terminology might be a bit shaky. I'm looking to dynamically load different templates within a specific section of a page based on user clicks without altering the URL path. I know how to use $routeProvider with ...

Guide to conditionally adding a property to an object in JavaScript

After scouring both Stack Overflow and Google for a solution, I finally stumbled upon this brilliant idea: x = { y: (conditionY? 5 : undefined), z: (conditionZ? 5 : undefined), w: (conditionW? 5 : undefined), v: (conditionV? 5 : undefined), u ...

React-pdf has encountered a situation where more hooks were rendered compared to the last render cycle

I am currently integrating react-pdf to display a PDF document in a web view. The React application is built with TypeScript and Next.js. This is the code I have written so far: const MyPage: NextPage = () => { // some code here const [numPages, setN ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...