Graph plot in a responsive div using Plotly.js

My project involves creating a webpage with dynamic div elements that resize upon mouseover using a straightforward CSS class. I've set it up so that these divs start off small when the page loads, but expand when a user hovers over them.

The CSS code looks something like this:

.resize {
    width: 400px;
    height: 300px;
    transition: all 1s;
}

.resize:hover {
    width: 800px;
    height: 600px;
}

I am currently working on making the plots generated by Plotly.js within these divs automatically adjust their size as the user hovers over them.

Here's the JavaScript function for creating the graphs:

function doGraph() {
    for(index = 0; index < divArr.length; ++index) {
        (function() {
            var d3 = Plotly.d3;

            var gd3 = d3.select("div[id='"+divArr[index]+"']");
                //.append('div')
                //.style({
                //    width: "95%", "margin-left": "2.5%",
                //    height: "95%", "margin-top": "2.5%"
                //});

            var gd = gd3.node();

            Plotly.newPlot(gd, [{
                mode:'lines',
                x: xArr[index],
                y: yArr[index], }], 
                        layout , {scrollZoom:true,modeBarButtonsToRemove:['sendDataToCloud'],showLink:false,displaylogo:false});

            window.addEventListener('resize', function() { Plotly.Plots.relayout(gd); });

        })();
    }
}

The section of commented out code indicates where I'm uncertain about how to make everything function as intended. I've tried various approaches without success so far.

All the content on the page is dynamically generated in C# code based on text files provided by users.

A related question that I came across can be found here, but I'm unsure if and how it applies to my specific implementation.

Answer №1

Check out plotly's resize feature.

The graph in the code snippet below adjusts its size randomly when hovered over. Feel free to customize it according to your requirements.

(function() {
  var d3 = Plotly.d3;

  var WIDTH_IN_PERCENT_OF_PARENT = 60,
    HEIGHT_IN_PERCENT_OF_PARENT = 80;

  var gd3 = d3.select('#myDiv')
    .style({
      width: (Math.random() + Math.random()) * WIDTH_IN_PERCENT_OF_PARENT + '%',
      'margin-left': (100 - WIDTH_IN_PERCENT_OF_PARENT) / 2 + '%',

      height: (Math.random() + Math.random()) * HEIGHT_IN_PERCENT_OF_PARENT + 'vh',
      'margin-top': (100 - HEIGHT_IN_PERCENT_OF_PARENT) / 2 + 'vh'
    });

  var gd = gd3.node();

  a = Plotly.plot(gd, [{
    type: 'bar',
    x: [1, 2, 3, 4],
    y: [5, 10, 2, 8],

  }], {
    title: 'Graph resizes randomly on hover',
    font: {
      size: 16
    }
  });

  document.getElementById("myDiv").on('plotly_hover', function(data) {
    window.alert("Resizing now");
    gd3 = d3.select('#myDiv')
      .style({
        width: (0.5 + Math.random() + Math.random()) * WIDTH_IN_PERCENT_OF_PARENT + '%',
        height: (0.5 + Math.random() + Math.random()) * HEIGHT_IN_PERCENT_OF_PARENT + 'vh',
      });
    gd = gd3.node()
    Plotly.Plots.resize(gd);;
  });


})();
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id='myDiv'></div>


(function() {
  var d3 = Plotly.d3;

  var WIDTH_IN_PERCENT_OF_PARENT = 60,
    HEIGHT_IN_PERCENT_OF_PARENT = 80;

  var gd3 = d3.select('#myDiv')
    .style({
      width: WIDTH_IN_PERCENT_OF_PARENT + '%',
      'margin-left': (100 - WIDTH_IN_PERCENT_OF_PARENT) / 2 + '%',

      height: HEIGHT_IN_PERCENT_OF_PARENT + 'vh',
      'margin-top': (100 - HEIGHT_IN_PERCENT_OF_PARENT) / 2 + 'vh'
    });

  var gd = gd3.node();

  a = Plotly.plot(gd, [{
    type: 'bar',
    x: [1, 2, 3, 4],
    y: [5, 10, 2, 8],

  }], {
    title: 'Double size on hover, return to normal on unhover',
    font: {
      size: 16
    }
  });

  document.getElementById("myDiv").on('plotly_hover', function(data) {
    gd3.style({
        width: 2 * WIDTH_IN_PERCENT_OF_PARENT + '%',
        height: 2 * HEIGHT_IN_PERCENT_OF_PARENT + 'vh',
      });
    gd = gd3.node()
    Plotly.Plots.resize(gd);;
  });

  document.getElementById("myDiv").on('plotly_unhover', function(data) {
    gd3.style({
        width: WIDTH_IN_PERCENT_OF_PARENT + '%',
        height: HEIGHT_IN_PERCENT_OF_PARENT + 'vh',
      });
    gd = gd3.node()
    Plotly.Plots.resize(gd);;
  });


})();
<script src="https://cdn.plot.ly/plotly-1.2.0.min.js"></script>
<div id='myDiv'></div>

Answer №2

Transforming a div into a resizable element is achievable by applying the style properties resize:both; overflow: auto. Plotly's responsiveness to window resizing can be enhanced by setting the configuration option responsive: true, enabling synchronization between div and window resize events. The method of detecting div resizing is elaborated at this link. To see these principles in action, check out this demo on JSFiddle.

<html>
<head>
  <script type="text/javascript" src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>

<div id='myDiv' style="resize:both; overflow: auto; border: 1px solid; height:250px">
</div>

<script>

let observer = new MutationObserver(function(mutations) {
  window.dispatchEvent(new Event('resize'));
});

let child = document.getElementById('myDiv');
observer.observe(child, {attributes: true})

var trace1 = {
  type: 'bar',
  x: [1, 2, 3, 4],
  y: [5, 10, 2, 8],
}

var data = [trace1]
var layout = {
  margin: {l: 20, r: 10, b: 20, t: 10}
}
var config = {responsive: true}

Plotly.newPlot('myDiv', data, layout, config);
</script>

</body>
</html>

Answer №3

As per the information found on resizing elements, the parameter responsive is included in the configuration:

var settings = {responsive: true}

Plotly.newPlot('myContainer', dataset, design, settings );

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

XSLT issue with Internet Explorer 11 - unable to transform XML file

Attempting to display an XSLT stylesheet that is retrieved from an API. It seems to be rendering correctly on Chrome and Firefox, but not on Internet Explorer. I have tried using the example provided by W3C, which works perfectly fine, but it fetches the ...

Steps to dynamically populate dropdown menus based on the selected options from other dropdown menus

I am working on a project that involves two dropdown menus. The options for the first dropdown menu are stored in a file called constant.ts. Depending on the selection made in the first dropdown, the options for the second dropdown will change accordingly. ...

The UI in an angular directive is not getting refreshed due to issues with the

Check out this fiddle http://jsfiddle.net/3jos4pLb/ I have a problem where my directive communicates with the parent controller scope by setting the finalValue. However, when the window is resized, the scope.finalValue updates in the console but the UI d ...

Exploring the application of conditional logic within HTML coding

I am working on ensuring that Part II of the HTML page only runs once all required information has been successfully submitted through the form. This particular issue is within a Flask application. I need to run Part II after Part I in order to prevent an ...

What is causing my Nuxt.js application to show a blank page following deployment on Netlify?

Currently, I am facing an issue while trying to deploy a Nuxt.js site using Netlify and Heroku. Although my build passes on Netlify, the link displays a blank page (). Despite following various online tutorials and adapting solutions from SO for react apps ...

What is a clever way to code this Angular HTML using just a single <a> tag?

<ul> <li ng-repeat="channel in Board.Channels"> <a ng-if="channel.key == ''" ng-href="/{{Board.type}}/{{Board.id}}/{{Board.key}}">{{channel.title}}</a> <a ng-if="channel.key != '&apo ...

When interacting with Chrome, the div gets automatically blurred upon being clicked

While working on the development of our website, we stumbled upon something peculiar. We have a set of divs displayed on the screen, resembling the layout of Pinterest. Upon clicking any of these divs, the content within that particular div is loaded into ...

The validation of class names in jQuery is not functioning correctly for text fields that are dynamically

I am currently experiencing an issue with jQuery Validation in regards to validating dynamically generated text fields through AJAX... Highlighted below is a snippet of the HTML code: <form name="booking" id="booking" method="post" action=""& ...

Having difficulty dynamically updating a button's state based on the number of elements in a list

This particular app follows the MAUI framework. Within MainPage.xaml, the XAML code looks like this: <Button x:Name="SendPhotoBtn" Text="Send Photos" SemanticProperties.Hint="Send photos to ...

How to incorporate an $gte/$lt condition within an $in operator in node.js with MongoDB

Using the MongoDB Node.js driver, my query is structured as follows: var query = { $and: [{ "custom_date": { "$gte": minDateValue, "$lt": maxDateValue } }, {"doc_name": {"$in": fil ...

Having trouble getting my image to appear at the top of the website, could it be an alignment issue?

Here is a screenshot showing the issue: https://i.stack.imgur.com/kSVQj.png. The quote on my website does not align to the top as expected. Can anyone provide a solution for this? Below is the corresponding code: <body> <div id="container"> ...

"Table layout set to fixed is failing to function as intended

Can someone help me figure out why the CSS table in the code below is not hiding the content that exceeds the table height of 200px? Instead, the table is expanding vertically. <div style='display:table; border:1px solid blue; width:200px; table ...

Update submenu panel in jQuery Mobile version 1.4.3 following AJAX request

Hello there, I am currently in the process of developing my first JQuery Mobile website. One of the key features I have implemented is a panel for navigation. Each individual page includes the panel, along with an icon in the header that serves as the butt ...

The Codepen demo for SemanticUI is not functioning properly

Click here to view the example on CodePen $('.ui.sidebar').sidebar({ context: $('.bottom.segment') }) .sidebar('attach events', '.menu .item'); I am currently trying to replicate this specific functiona ...

What are the differences between a Chrome app and extension? Is there any other way to access the tabs currently open in your

I need to develop an app that can access the tabs a user has open, but I'm struggling to find a way to do so without having my app run in Chrome itself. Creating an extension restricts the UI significantly, which is problematic since my app requires a ...

Having trouble with updating your website asynchronously through code? In need of a detailed explanation?

Here are two Javascript functions that are used to call a python file in order to update an HTML page. The first function works perfectly fine, but the second one seems to be malfunctioning without throwing any errors. function button(key) { var xhttp ...

What could be causing the content to disappear when switching from flex: column to flex: row?

In the code snippet provided below, you may notice that when the screen size is less than 768px, the video and content underneath it are visible. However, as soon as the screen size exceeds 768px, the video disappears. Have you ever wondered why the video ...

Guide to setting up a multi-column grid system with Bootstrap and CSS

Trying to create a grid layout using Bootstrap, I need some assistance. Check out the image for reference: enter image description here Here's the code I've been working on, but I can't seem to get it right: <section id="section-2&q ...

Uploading a JSON file in Azure Cosmos DB using C#/.NET

Is there a way to directly upload a JSON file to my Azure Cosmos DB container without having to deserialize and convert it into a C# object first? container.CreateItemAsync(myData.json) ...

Modifying material in Three.js

My method for selecting geometry involves using the numbers on my keyboard, as shown below: if(keyboard.pressed("1")){ obj = torus; } This allows me to toggle their visibility: if(keyboard.pressed("a")){ THREE.SceneUtils.traverseHierarchy( obj, fu ...