Controlling Color Transparency with Value

I am working with a TreeMap layout and want to adjust the opacity of the children rectangles based on their values. Additionally, I would like each child to have a specific fill color so that viewers can easily compare data between cities without needing a separate legend. Currently, all rectangles in the TreeMap are the same color.

Apologies for directly inputting data into the code - I am still learning the basics.

Cheers

<!DOCTYPE html>
<meta charset="utf-8">
<head>
  <title>TreeMap</title>
  <link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>

<body>
  <svg width="1200" height="720">
    <g></g>
    <section class="container1">
      <p class="p1"> North England </p><p class="p2"> South England </p>
      <p class="p3"> Bradford City </p><p class="p4"> Leeds </p>
      <p class="p5"> Liverpool </p><p class="p6"> Manchester </p>
      <p class="p7"> Sheffield </p><p class="p8"> Brighton </p>
      <p class="p9"> Bristol </p><p class="p10"> Luton </p>
      <p class="p11"> Milton Keynes </p><p class="p12"> Southampton </p>
      <object class="Box" class="cancer"></object>
    </section>
  </svg>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
  <script>
var data = {
  "name": "England",
  "children": [
    {
      "name": "North England",
      "children": [
        {
          "name": "Bradford City",
          "children": [
            {
              "name": "Cancer",
              "value": 1.18,
              "color": "#A8A7A7",
            },
            {
              "name": "CKD",
              "value": 3.21,
              "color": "#2F9599",
            },
            {
              "name": "CHD",
              "value": 2.57,
              "color": "#E8175D",
            },
            {
              "name": "Diabetes",
              "value": 11.92,
              "color": "#474747",
            },
            {
              "name": "Stroke",
              "value": 1.18,
              "color": "#CC527A",
            }
          ]
        },

// Remaining code not changed for brevity

 

Answer №1

To adjust the opacity attribute, similar to setting width or height, you can define a function that determines how your values should be mapped into the percentage range (taking into consideration the maximum value).

.attr('opacity', function(d) { return d.value / 10 })

Incorporating this concept into your code would look something like this:

<!DOCTYPE html>
<meta charset="utf-8">
<head>
  <title>Pack layout (with labels)</title>
</head>;

<style>
rect {
  stroke: white;
}
text {
  font-family: "Helvetica Neue", Helvetica, sans-serif;
  fill: black;
  font-size: 8px;
  text-anchor: end;
}

svg {
  padding-left: 60px;
  padding-top: 40px;
}
</style>

<body>
  <svg width="1020" height="720">
    <g></g>
  </svg>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
  <script>
var data = {
  "name": "North England",
  "children": [
    {
      "name": "Bradford City",
      "children": [
        {
          "name": "Cancer",
          "value": 1.18,
          "color": "red",
        },
        {
          "name": "CKD",
          "value": 3.21,
          "color": "green",
        },
        {
          "name": "CHD",
          "value": 2.57,
          "color": "blue",
        },
        {
          "name": "Diabetes",
          "value": 11.92,
          "color": "yellow",
        },
        {
          "name": "Strokes",
          "value": 1.18,
          "color": "gray",
        }
      ]
    }
  ]
};

var treemapLayout = d3.treemap()
  .size([600, 400])
  .paddingOuter(20);

var rootNode = d3.hierarchy(data)

rootNode.sum(function(d) {
  return d.value;
});

treemapLayout(rootNode);

var nodes = d3.select('svg g')
  .selectAll('g')
  .data(rootNode.descendants())
  .enter()
  .append('g')
  .attr('transform', function(d) {return 'translate(' + [d.x0, d.y0] + ')'})

nodes
  .append('rect')
  .attr('width', function(d) { return d.x1 - d.x0; })
  .attr('height', function(d) { return d.y1 - d.y0; })
  .attr('opacity', function(d) { return 0.5 /* has to be like d.value / max or so */ })
  .attr('fill', function(d) { if (d.data.color) { 
                                  return d.data.color 
                                } else {
                                  return "white"
                                }})

nodes
  .append('text')
  .attr('dx', 4)
  .attr('dy', 14)
.text(function(d) {
      return d.data.name;
  });
  

  </script>
</body>

Updated:

    <!DOCTYPE html>
<meta charset="utf-8">
<head>
  <title>TreeMap</title>
  <link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>

<body>
  <svg width="1200" height="720">
    <g></g>
    <section class="container1">
      <p class="p1"> North England </p><p class="p2"> South England </p>
      <p class="p3"> Bradford City </p><p class="p4"> Leeds </p>
      <p class="p5"> Liverpool </p><p class="p6"> Manchester </p>
      <p class="p7"> Sheffield </p><p class="p8"> Brighton </p>
      <p class="p9"> Bristol </p><p class="p10"> Luton </p>
      <p class="p11"> Milton Keynes </p><p class="p12"> Southampton </p>
      <object class="Box" class="cancer"></object>
    </section>
  </svg>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
  <script>
var data = {
  "name": "England",
  "children": [
    {
      "name": "North England",
      "children": [
        {
          "name": "Bradford City",
          "children": [
            {
              "name": "Cancer",
              "value": 1.18,
              "color": "#A8A7A7",
            }
            ...
          ]
        }
        ...
      ]
    }
    ...
  ]
};

var maxValues = {
  "Cancer": 2.54,
  "CKD": 5.9,
  "CHD": 3.85,
  "Diabetes": 12,
  "Stroke": 2.13,
}

var treemapLayout = d3.treemap()
  .size([1000, 600])
  .paddingTop(20)
  .paddingInner(8);

var rootNode = d3.hierarchy(data)

rootNode.sum(function(d) {
  return d.value;
});

treemapLayout(rootNode);

var nodes = d3.select('svg g')
  .selectAll('g')
  .data(rootNode.descendants())
  .enter()
  .append('g')
  .attr('transform', function(d) {return 'translate(' + [d.x0, d.y0] + ')'});

nodes
  .append('rect')
  .attr('width', function(d) { return d.x1 - d.x0; })
  .attr('height', function(d) { return d.y1 - d.y0; })
  .attr('opacity', function(d) { return d.value / maxValues[d.data.name] })
  .attr('fill', function(d) { if (d.data.color) {
                                  return d.data.color
                                } else {
                                  return "white"
                                }});
  
nodes
  .append('text')
  .attr('dx', 10)
  .attr('dy', 8)
      .text(function(d) {
      return d.data.value;
  });

  </script>
</body>

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

What is the reason for the click event in a Chrome extension's popup to refresh the popup's

While exploring Chrome extensions, I came across a strange issue with the popup window. Inside popup.html, there is an element <a id="grantexpert">...</a> and in popup.js, I want to change the background color of this element when clicked. Ini ...

Refreshing the Date Display with AJAX Response

Within a view, there is a DisplayFor connected to a DateTime field in the Model. After an AJAX call returns a Date to update the field, I am able to convert the AJAX date into a MM/DD/YYYY format. However, using .val to set the DisplayFor does not reflect ...

Is there a way to access a PHP value within a self-invoked jQuery function?

I have a page that creates n links using a foreach loop: ...some html and php code <?php foreach ($tables as $table):?> ... some elements generated ... <td><a onclick="setPortalId(<?php echo $table['id']?>);$('#file ...

There was an unexpected token syntax error while trying to assign the database URL from the environment variable "REACT_APP

I am facing an issue with setting an environment variable in my mongo.js file. Here is the code snippet where I have set the ENV variable: const mongo = require('mongodb').MongoClient; const assert = require('assert'); const ObjectId = ...

Create a custom slider using jQuery that pulls in real-time data for a dynamic user

My goal is to implement a dynamic slider feature in my Django project by using jQuery and ajax. I have managed to create previous and next buttons for swiping through profiles with the help of others, but I am currently facing an issue with a NoReverseMatc ...

Styling the React Material UI DataGrid with the MuiDataGrid-window class using createMuiTheme or makeStyles / styled-components

I've been putting in a lot of effort to customize the css for the .MuiDataGrid-window in MaterialUi's DataGrid. I've been referencing css rules from https://material-ui.com/api/data-grid/ I managed to get it working within createMuiTheme fo ...

multiple event listeners combined into a single function

I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one eve ...

How can I automatically add and remove the active class to the navigation on a single page layout?

Is there a way to automatically add an active class to the navbar links when a specific navigation section appears as you scroll down a one-page layout? Similarly, can the active class continue to move to the corresponding section in the nav links as you s ...

Adding a tooltip to a specific header in a Vue list - here's how!

My goal is to add a tooltip to a specific header labeled 'Retire' within a data table, without affecting any of the other headers. It's been quite the learning experience for me as a Vue novice, but with the help of AI (chatgpt), I've m ...

Difficulty in eliminating left and right padding in Vuetify's Toolbar component despite attempts with spacing helpers

The v-toolbar component features default padding of 24px on the left and right each in the desktop version. Unfortunately, this padding cannot be overridden. I attempted to utilize Vuetify's spacing helpers (pa-0, ma-0), but they only end up shifting ...

Automatically adjust text size within div based on width dimensions

Dealing with a specific issue here. I have a div that has a fixed width and height (227px x 27px). Inside this div, there is content such as First and Last name, which can vary in length. Sometimes the name is short, leaving empty space in the div, but som ...

Sending an array from JavaScript to Ruby using Sinatra

My goal is to transfer a 2D array from JavaScript to something that Ruby can interpret. All elements in the array are strings. I have been using gon-sinatra, but it doesn't fulfill all my requirements. I tried storing the string I want to pass in &ap ...

Selenium WebDriver is having trouble locating an element

Currently, I am employing the latest version of selenium webdriver. The issue arises when Selenium fails to locate an element (specifically an input field). Here is the relevant HTML code: <input id="findPath" class="pathCom" type="text" style="width: ...

The video on mobile is not loading properly, as the play button appears crossed out

There seems to be an issue with GIFs not loading on mobile devices, even though they are implemented as mobile-ready. <video src="/wp-content/uploads/2017/09/5.mp4" preload="metadata" autoplay="autoplay" loop="loop" muted="muted" controls="controls" ...

Confirm the presence of Cookie and save the data

I'm a beginner in the world of Javascript and Ajax, attempting to save a user's name using cookies. I have created a form where users can input their first name (identified by id = firstName). My goal is to remember this information so that the n ...

Create a random number within a specified range using a different number in JavaScript

I am looking for a unique function that can generate a number within a specified range, based on a provided number. An example of the function would be: function getNumber(minimum, maximum, number) { ... } If I were to input: getNumber(0, 3, 12837623); ...

Step by step guide to applying a personalized "margin" to your CSS

I have set the body element's margin to 0 in my CSS stylesheet. However, I am struggling to successfully set the margin for the div elements. Therefore, I would like to set all other things' margin to 0; except for the div elements with the cl ...

nanoExpress Route Isolation

I am facing an issue while trying to separate route directories in my project. The error I encountered is as follows: rror [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './cjs' is not defined by "exports" in /mnt/.../projects/.../nan ...

The mobile view is not displaying the footer in full width as expected

I am currently working on designing a website without using the meta viewport tag. My goal is to ensure that my website displays properly on both mobile and desktop devices. I have encountered an issue with the comparison between the home page (index) an ...

Tips for implementing a client-side event when an asp:menu item is clicked

Currently, I'm incorporating the <asp:Menu> control into my website and populating it with data from a table in my Sql Server database using an XML data source. Now, I am looking to implement a client-side event when a user clicks on a menu item ...