Creating a horizontal bar graph using d3.js

After creating a horizontal bar graph, I encountered several issues that need to be addressed:

  • I could not hide the labels associated with the X major axis.
  • I need to create dotted lines for values at 80% and 100%.
  • I want rounded edges on the bar graph.
  • Add a legend to the bar graph.

Below is the current code in use:

<!DOCTYPE html>
<meta charset="utf-8">
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v6.js"></script>
  
<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<script>

// set the dimensions and margins of the graph
const margin = {top: 20, right: 30, bottom: 40, left: 90},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body page
const svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", `translate(${margin.left}, ${margin.top})`);

// Parse the Data
d3.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/7_OneCatOneNum_header.csv").then( function(data) {

  // Add X axis
  const x = d3.scaleLinear()
    .domain([0, 1000])
    .range([ 0, width]);
  svg.append("g")
    .attr("transform", `translate(0, ${height})`)
    .call(d3.axisBottom(x).tickSize(0))
    .select(".domain").remove();

  // Y axis
  const y = d3.scaleBand()
    .range([ 0, height ])
    .domain(data.map(d => d.Country))
    .padding(.1);
  svg.append("g")
    .call(d3.axisLeft(y).tickSize(0));

  //Bars
  svg.selectAll("myRect")
    .data(data)
    .join("rect")
    .attr("x", x(0) )
    .attr("y", d => y(d.Country))
    .attr("width", d => x(d.Value))
    .attr("height", y.bandwidth())
    .attr("fill", "#69b3a2");

})

</script>

Current Output:

https://i.sstatic.net/2w2AR.png https://i.sstatic.net/rJPq5.png

Edit 1:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<meta charset="utf-8">
...

Current Output After Edit 1:

https://i.sstatic.net/08ejP.png

Edit 2: Problems that still remains

  1. Grid lines
  2. Legends

Updated Code

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<meta charset="utf-8">
...

Edit 2 Output:

https://i.sstatic.net/z3SsZ.png

Edit code suggested by Omar:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<meta charset="utf-8">
...

Current Output:

https://i.sstatic.net/hQTif.png For any help, I would greatly appreciate it. Thank you in advance!

Answer №1

Here is a guide for adding dashed lines:

svg.append("line")
        .attr("class", "avgValue")
        .attr("x1", 0.8 * (width/2))
        .attr("y1", "0")
        .attr("x2", 0.8 * (width/2))
        .attr("y2", height)
        .attr("stroke", "purple")
        .attr("stroke-width", "1")
        // The first value in stroke-dasharray refers to the length of a dash, and the second refers to the spacing between dashes
        .style("stroke-dasharray", ("10,4"))
      
      svg.append("line")
        .attr("class", "maxValue")
        .attr("x1", width/2)
        .attr("y1", "0")
        .attr("x2", width/2)
        .attr("y2", height)
        .attr("stroke", "blue")
        .attr("stroke-width", "1")
        .style("stroke-dasharray", ("10,4"))

I have adjusted your rounded corners function for better alignment. Here's the updated code:

function rightRoundedRect(x, y, width, height, radius) {
      return `M ${x},${y}
              h ${width-radius}
              q ${radius},0 ${radius},${radius}
              v ${height - (2*radius)}
              q 0,${radius} -${radius},${radius}
              h -${width - radius}
              z`
    }

This section shows how these changes reflect in your code:

Your unique content here.

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

Finding the current cursor position in a Shiny textareaInput

Is there a way to determine the cursor position within a textAreaInput in a shiny application? library(shiny) ui <- fluidPage( textAreaInput("hop" ,label="textarea",value = "Supercalifragilisticexpialidocious"), verbatimTextOutput( ...

A foolproof method for confirming an object is an EcmaScript 6 Map or Set

Can someone help me verify if an object is a Map or Set, but not an Array? For checking an Array, I currently use lodash's _.isArray. function myFunc(arg) { if (_.isArray(arg)) { // doSomethingWithArray(arg) } if (isMap(arg)) { // doS ...

How to transform a string into a nested array in JavaScript

I created a list using Django and passed it to index.html. However, I encountered an issue when trying to use it in the JavaScript content. The list is being passed as a string, and although I attempted to use JSON.parse, I received an error message: Unc ...

Locate the internal IP address of an Express server

Currently, I have a Node express server up and running on Machine 1 with the IP address of (0.0.0.0). On separate machines such as Machine 2, 3, and others, there are client applications also connected to the same Wi-Fi network. My query is how do I obtai ...

Generate a JSON object based on the request.body information

Currently using NodeJs along with Express for building a REST API. The functionality is all set up and running smoothly, but I'm facing an issue in comprehending how to iterate through the request.body object and validate its fields for any undefined ...

Assistance needed in keeping an image with absolute positioning CSS fixed to the top left corner of the browser

Looking for some CSS help as a beginner here! I've been trying to position a transparent PNG image over a centered table, but it seems stuck in the upper left corner of the browser. Absolute positioning should give me freedom to move it around, right? ...

Attempting to input information into a form and then showcase the data both on the current page and in a separate pop-up window

Each time I complete the entire form, the data vanishes. However, if I only input three fields, it displays properly. But as soon as I enter the last piece of data and click on display, everything gets erased. Moreover, I also require the data to be shown ...

Retrieve the body's coordinates when dragging an element using the jQuery UI library

How can I obtain the coordinates of a dragged div upon drag and drop action, including left, right, and top positions? Additionally, how do I then use Ajax to post these coordinates? An example link can be found at jsfiddle.net/qPw92 <html> &l ...

JQuery method for extracting a specific span's content from a div

I am faced with extracting specific text from a span within a div element. Below is the code snippet for my Div: '<div class="dvDynamic_' + pid + '"><p hidden="true">'+pid+'</p><span class="count_' + pid ...

Using Jquery to create interactive and dynamic webpage elements

I am struggling with a paragraph containing words in a span that are editable upon clicking. The content needs to be dynamically called, but my current approach is not effective. Can anyone provide a solution or a better way to achieve this? Feel free to ...

"Struggling to make the 'overflow: hidden' property work for an absolutely positioned

I'm struggling to conceal an absolutely positioned image within a CSS grid layout. Below is the code snippet: HTML: <div class="relative-parent"> <div v-for="item in 12" class="hiding-parent"> <div c ...

obtain the string representation of the decimal HTML entity value

Similar Question: how to create iphone apps similar to ibeer, imilk, ibug, ibeer Using javascript to obtain raw html code Imagine having an html section like this: <div id="post_content"> <span>&#9654;<span> </div> ...

Modify the click function from <tr> to <td> tag

I want to create an HTML page that functions as a digital library for books. Users should be able to click on a rate button to save the selected book to local storage, allowing them to see their rating whenever they revisit the page. However, I'm enc ...

The float property is not functioning properly in CSS right now

I am a novice when it comes to CSS and I am attempting to position my information icon on the right side of my webpage. Below is the HTML and CSS code that I currently have: .content > .chat-section > .chat-window > .chat-top-bar { ...

Reposition the checked box to the top of the list

My goal is to click on each item, and the selected item should move to the top of the list and be rendered at the top. However, I encountered an issue where when clicking on an item, it moves to the top but the item that replaces it also gets checked. Bel ...

Is it possible to utilize ember-cli solely as a frontend tool, much like how we use JavaScript and jQuery?

Is it feasible to employ ember-cli exclusively as a front-end tool, similar to utilizing JavaScript and jQuery? I am interested in incorporating a reference to ember-cli in my .NET project solely for validation purposes. Is this a viable approach, and an ...

What is the best way to incorporate TypeScript variables into CSS files?

In my Angular project, I am aiming to utilize a string defined in Typescript within a CSS file. Specifically, I want to set the background image of a navbar component using a path retrieved from a database service. Although I came across suggestions to use ...

Error Message: SCRIPT5 - Permission Denied When Trying to Open PDF with Javascript

Despite searching through multiple posts on SO, I have yet to find a solution to my issue. We operate a web form within our LAN that utilizes Javascript's OPEN function to open PDF files. Up until recently, everything was working smoothly. However, ...

"Use jQuery to toggle the slide effect for the first element of a

Below is the HTML code snippet: <div class="row header collapse"> Content 1 <i class="fas fa-chevron-circle-up" ></i> </div> <div class="instructions-container"> <div></di ...

Utilizing a Frozen Tensorflow Model with NodeJS for High-Performance Computing

I am new to tensorflowjs and js in general, but I have a trained model that I need to run on it. I have converted the model to json format, but I am having trouble feeding data into it: const tf = require('@tensorflow/tfjs') const tfn = require( ...