Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Responsive and animated <a href="https://d3js.org/">D3.js</a> bar chart with positive and negative values (TypeScript)</h1>

<p>
  <button id="update-bar-chart">Update chart</button>
</p>

<div class="container">
  <div id="barchart" class="barchart"></div>
</div>

              
            
!

CSS

              
                html, body {
  color: #333;
  font-size: 16px;
  line-height: 20px;
}
body {
  margin: 20px;
}

h1 {
  line-height: 1.2;
  margin: 0 auto 35px;
  max-width: 800px;
  text-align: center;
}

p {
  text-align: center
}

button {
  padding: 5px 10px;
}

.container {
  margin: 0 auto 35px;
  max-width: 800px;
}

.barchart {
  border: 1px solid #eee;
}

              
            
!

JS

              
                interface ChartInterface {
  create(),
  setData(data: any[]),
  setElement(element: HTMLElement),
  setOptions(options: {[name: string]: any})
}

class BarChart implements ChartInterface {
  private element: HTMLElement
  private data: any[]
  private minValue: number
  private maxValue: number
  private svg: any
  private options: {[name: string]: any} = {
    colors: {
      highlight: '#b11adc',
      highlightLight: '#d975f6',
      text: '#777',
      xAxis: '#eee',
      yAxis: '#999'
    },
    height: 480,
    width: 360,
    margin: {
      top: 10,
      left: 30,
      right: 10,
      bottom: 20
    },
    animationDuration: 300,
    ticksInterval: 10
  }
  private yScale: any
  private xScale: any

  public create() {
    this.initValues()
    this.initScales()
    this.initChart()
    this.createAxis()
    this.createBars()
  }
  
  public setData(data: any[]) {
    this.data = data
  }

  public setElement(element: HTMLElement) {
    this.element = element
  }

  public setOptions(options: {[name: string]: any}) {
    this.options = {
      ...this.options,
      ...options
    }
  }

  private initChart() {
    const el = d3.select(this.element)
    
    el.select('svg').remove()

    this.svg = el.append('svg').attr(
      'viewBox', 
      `0 0 ${this.options.width} ${this.options.height}`
    )
    
    const isIE = () => {
      const ua = navigator.userAgent
      return ua.match(/Trident\/7.0/) || ua.match(/Trident\/6.0/)
    }
    
    if (isIE()) {
      this.svg.attr('width', this.options.width)
      this.svg.attr('height', this.options.height)
    }
  }

  private initValues() {
    const minValue = Number(d3.min(this.data.map(el => el.value)))
    const maxValue = Number(d3.max(this.data.map(el => el.value)))

    this.minValue = minValue < 0 ? minValue - this.options.ticksInterval : 0
    this.maxValue = maxValue + this.options.ticksInterval
  }
  
  private initScales() {
    this.yScale = d3
      .scaleLinear()
      .domain([this.minValue, this.maxValue])
      .range([
        this.options.height - this.options.margin.bottom, 
        this.options.margin.top
      ])
    
    this.xScale = d3
      .scaleBand<number>()
      .domain(d3.range(this.data.length))
      .range([
        this.options.margin.left + this.options.margin.right, 
        this.options.width - this.options.margin.right
      ])
      .paddingInner(this.calculatePadding(this.data.length))
  }
  
  private getBarMaxWidth() {
    const width = window.innerWidth
    return width <= 768 ? width <= 480 ? 10 : 15 : 20
  }
  
  private getBarColor(i: number, change: number = 0) {
    const red = (210 + change).toString()
    const green = ((10 + 20 * i) + change).toString()
    const blue = ((220 - 20 * i) + change).toString()
    return `rgb(${red}, ${green}, ${blue})`
  }

  private createBars() {
    const bars = this.svg
      .selectAll('.bar')
      .data(this.data)
      .enter()
      .append('rect')
      .classed('bar', true)
      .style('fill', 'transparent')
      .style('display', (d) => typeof d.value === 'number' ? 'initial' : 'none')
      .attr('x', (d, i) => this.xScale(i))
      .attr('y', this.yScale(0))
      .attr('width', this.xScale.bandwidth())
      .attr('height', 0) 
    
    bars
      .transition()
      .style('fill', (d, i) => this.getBarColor(i))
			.duration(this.options.animationDuration)
			.delay((d, i) => i * this.options.animationDuration / 3)
      .attr('x', (d, i) => this.xScale(i))
      .attr('y', (d, i) => d.value < 0 ? this.yScale(0) : this.yScale(d.value))
      .attr('width', this.xScale.bandwidth())
      .attr('height', (d, i) => d.value < 0 ? this.yScale(d.value) - this.yScale(0) : this.yScale(0) - this.yScale(d.value))
    
    bars.on("mouseover touchstart", (d, i, nodes) => {
      const tick = d3.select(`.x-axis .tick:nth-child(${i+1}`)
      const color = this.getBarColor(i, 20)

      d3.select(nodes[i])
        .transition()
        .style('fill', color)

      tick.select('line')
        .transition()
        .style('stroke', color)

      tick.select('text')
        .transition()
        .style('fill', color)

    }).on("mouseout touchend", (d, i, nodes) => {
      const tick = d3.select(`.x-axis .tick:nth-child(${i+1}`)

      d3.select(nodes[i])
        .transition()
        .style('fill', this.getBarColor(i))

      tick.select('line')
        .transition()
        .style('stroke', this.options.colors.xAxis)

      tick.select('text')
        .transition()
        .style('fill', this.options.colors.text)
    })
  }
  
  private createAxis() {
    const xAxis = d3
      .axisBottom(this.xScale)
      .tickSize(-this.options.width)
      .tickFormat((d, i) => this.data[i].label.toUpperCase())
      
    const yAxis = d3
      .axisLeft(this.yScale)
      .tickSize(-this.options.width)
      .tickFormat(d => `${d} %`)
      .ticks(this.options.ticksInterval)

    this.svg
      .append('g')
      .attr('class', 'axis x-axis')
      .attr('transform', `translate(0, ${this.options.height-15})`)
      .call(xAxis)
    
    this.svg
      .append('g')
      .attr('class', 'axis y-axis')
      .attr('transform', `translate(${+this.options.margin.left}, 0)`)
      .call(yAxis)

    this.svg.selectAll('.axis .domain').remove()
    this.svg.selectAll('.axis .tick text').style('fill', this.options.colors.text)
    this.svg.selectAll('.y-axis .tick line').style('stroke', this.options.colors.yAxis)
    this.svg.selectAll('.x-axis .tick line').style('stroke', this.options.colors.xAxis)
  }
  
  private calculatePadding(barCount: number) {
    return 1 - (barCount * this.getBarMaxWidth() / this.options.width)
  }
}

class ChartRenderer {

  private chart: ChartInterface
  private data: any[]
  private element: HTMLElement

  constructor(chart: ChartInterface) {
    this.chart = chart
    this.initResize()
  }

  setData(data: any[]) {
    this.data = data
  }

  setElement(element: HTMLElement) {
    this.element = element
  }

  initResize() {
    let resizeTimer
    const resizeListener = () => {
      clearTimeout(resizeTimer)
      resizeTimer = setTimeout(() => {
        this.render()
      }, 200)
    }
    window.removeEventListener('resize', resizeListener)
    window.addEventListener('resize', resizeListener)
  }

  render() {
    const options = {
      width: this.element.offsetWidth,
      height: this.element.offsetWidth / 1.6
    }
    this.chart.setElement(this.element)
    this.chart.setData(this.data)
    this.chart.setOptions(options)
    this.chart.create()
  }
}

const getRandomData = (limit: number): any[] => {
  const chars = 'abcdefghijklmnopqrstuvwxyz'
  const getValue = () => {
    const value = Math.floor(Math.random() * 101) - 50
    return value === 0 || value === -1 || value === 1 ? 10 : value
  }
  return chars.substr(0, limit).split('').map(el => {
    return {
      value: getValue(),
      label: el
    }
  })
}

// Initialize chart
const renderer = new ChartRenderer(new BarChart())
renderer.setElement(document.getElementById('barchart'))
renderer.setData(getRandomData(12))
renderer.render()

// Update chart button
const updateButton = document.getElementById('update-bar-chart')
updateButton.onclick = () => {
  renderer.setData(getRandomData(12))
  renderer.render()
}

              
            
!
999px

Console