Trouble with displaying axis labels in a d3.js bar chart that is responsive

I have set up a sample codepen to showcase my problem. The issue at hand is that even though the axis labels are being successfully generated and added to the DOM, they are not visible as they are drawn outside of the chart area.

Below is the CSS I am using:

.promo {
  fill: rgba(255,0,0,0.5);
}

.price {
  fill: $brand-primary;
}

.chart {
  height: 50vh;
  width: 100%;
  overflow: hidden;
}

.svg-container {
    display: inline-block;
    position: relative;
    width: 100%;
    padding-bottom: 100%; /* aspect ratio */
    vertical-align: top;
    overflow: hidden;
}
.svg-content-responsive {
    display: inline-block;
    position: absolute;
    top: 0;
    left: 0;
}

And this is the JavaScript code in use:

let height = $('.chart').height();
let width = $('.chart').width();

let chart = d3.select('.chart')
    .append("div")
    .classed("svg-container", true) //container class for responsiveness
    .append("svg")
    .attr('preserveAspectRatio','xMinYMax meet')
    .attr('viewBox','0 0 '+width +' '+height )
    .classed("svg-content-responsive", true)
    .append('g');

// rest of the JS code follows...

The solutions I've found so far suggest adjusting margins for charts with fixed pixel sizes. However, since my chart is responsive (100% width and 50% viewport height), this approach isn't feasible. How can I resolve this issue to ensure my labels are displayed correctly?

Answer №1

After analyzing the chart above, I've noticed a few things. The SVG height and x axis seem to be starting from the same position, causing the axis to be hidden because the tick marks and text go beyond the viewbox of the SVG. To solve this issue, consider using the transform attribute to properly position the elements. Check out this JSFiddle for an example.

Adjusting the x axis position:

chart.append("g")
      .attr("class", "axis x")
      .attr("transform", "translate(0,"+(height -20)+")")
      .call(d3.axisBottom(x).ticks(10));

Grouping and positioning rectangles:

   var bar_g = chart.append("g")
   .attr('class','rectg')
   .attr("transform", "translate(0,"+(-20)+")");

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

Optimize Your Website for Various Screen Sizes

Can anyone assist with centering my webpage on small screen sizes? Everything looks good at the normal width of 989px, but once it shrinks, it shifts to the left and leaves excess white space on the right. I've tried various methods to correct this is ...

Confused about the sticky navigation, not sure what's happening here

Encountering an issue with my sticky nav. It seems like the JS is failing to apply the designated class. View it live here: Code snippet: <script> $(window).scroll(function() { var scroll = $(window).scrollTop(); nav = $('.nav-bar'). ...

Enhancing Material UI KeyboardDatePicker with personalized CSS design

Material UI KeyboardDatePicker is the component I'm currently using. https://i.sstatic.net/It50L.png In order to remove the black line visible in the datepicker (as shown in the screenshot), what steps should I take? Displayed below is the code ...

Selecting Child Elements in CSS

Suppose I have the below HTML structure: <div id="div1"> .... <span class="innercontents">...</span> .... </div> Is it possible to target only the child elements of a specific parent ID? For example, could I use this CSS rule? # ...

Creating HTML code for a mobile responsive design

I am facing an issue with my clinic webpage where the images appear differently on PC and mobile devices. I am new to HTML and CSS, so I tried using max-width: 100% but it didn't work. The code was originally created by someone else and I need help fi ...

Shifting text higher to the <h1> tag using CSS

I'm currently attempting to move the paragraph header closer to my h1 title. I'm struggling with incorporating the position function and have tried using padding without success. On the image, I am aiming to position the text "Where every connec ...

Make sure to define the image path in the CSS file of your WordPress project

When working on my WP 4.2 project, I encountered a situation in the CSS file where I had to write: background-image: url('/wp-content/plugins/artistssongs/images/fancybox_sprite.png'); However, I find it inconvenient to display the full path to ...

Optimizing CSS Breakpoints for Col-sm-X Classes: A Comprehensive Guide

My HTML code appears as follows: <Row> <Col class="col-xs-12 col-sm-12 col-md-4"> //Content here <Col> <Col class="col-xs-12 col-sm-12 col-md-4"> //Content here <Col> <Col class="col-xs-12 col-sm-1 ...

Customize the background color of selected date in MUI DatePicker 6.19.7 with sx styling

Looking to update the color of a specific element highlighted by an arrow using sx{} DatePicker <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker className={styles.picker} ...

Tips for making a slide-in animation that doesn't require adjusting the browser size

As I work on an animation where an img object and text slide in from outside the frame of the webpage upon page load, everything seems to be running smoothly. But there's one glaring issue: right at the start of the page load, the webpage resizes for ...

Optimal technique for implementing up and down arrows in a select dropdown

What's the most effective way to implement a percentage arrow up/down slider/selector within a select element on a webpage like this: https://i.sstatic.net/ygu55.png Should we use a select list with a dedicated background? If so, how do we detect i ...

Customizing color schemes of bootstrap buttons and dropdown-toggle elements

My button group looks like this: HTML <div class="btn-group"> <button type="button" class="btn btn-default btn-xs red-outline-button"> Sync </button> <button type="button" class="btn btn-default btn-xs gold-outline-button" da ...

Maintaining consistent height across all elements in a column while preserving margin: a guide

My query revolves around filling the contents of two columns with different heights within a row. Although the columns themselves are of equal height, the cards inside them are not. +---------------------------+---------------------------+ | +------------- ...

Is there a way to modify or update the CSS classes and overall styling in .gsp files within the Grails framework?

What is the best way to dynamically update a DOM element's class and styling in response to specific conditions or events occurring in a .gsp file? ...

Adjust the width of individual columns in Bootstrap 4 responsive tables to ensure they have specific widths

I am currently working on setting up a table where specific columns require a fixed width and do not adjust automatically. Despite attempting a method to achieve this, I have encountered issues as the width still adjusts based on the length of the text. ...

Tips for aligning two divs of varying sizes side by side

Imagine having two div elements: <div id="container"> <div id="left">line one</div> <div id="right">line one<br/>line two</div> </div> Is there a way to have the left and right divs align at the bottom li ...

Utilizing Reactjs and typescript to dynamically set width and height properties of a div element using randomly generated variables

I am attempting to set a randomly generated variable as the width and height of a div. I have successfully written a function that generates a random size, but encounter an error when trying to assign it to the style attribute. My objective is to create a ...

Should servlet response be HTML for use in AJAX calls?

I am currently in the process of developing a web application with multiple pages, including index.html which serves as the main page and contains various <a> tabs linking to different Servlet pages. As part of my design, I have a consistent CSS lay ...

Fetch colors from an API to dynamically update the colors in tailwind.config.ts using Next.js

When I decided to incorporate SEO into my React project, I opted for Next.js. However, I encountered an issue when trying to load colors from the backend to be used in tailwind.config.ts. Does anyone know how to accomplish this with Next.js? ...

Issues are arising with Bootstrap's functionality within the Vite React app

I am new to working with react and vite. I am currently developing a vite react application that requires the use of bootstrap. I followed the instructions provided on the official Bootstrap website here. However, not all Bootstrap functionalities are work ...