css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script src="https://d3js.org/d3.v5.min.js"></script>
</body>
</html>
            
          
!
            
              body {
      font-family: 'Open Sans', sans-serif;
      width: 1000px;
      height: 600px;
      margin: auto;
      background-color: #2F4A6D;
    }

    .bar {
      fill: #80cbc4;
    }

    rect {
      cursor: pointer;
    }

    text {
      font-size: 12px;
      fill: #fff;
    }

    path {
      stroke: gray;
    }

    line {
      stroke: gray;
    }

    .grid path {
      stroke-width: 0;
    }

    .grid .tick line {
      stroke: #9FAAAE;
      stroke-opacity: 0.3;
    }
            
          
!
            
              const sample = [
  {
    language: 'Rust',
    value: 78.9,
    color: '#000000'
  },
  {
    language: 'Kotlin',
    value: 75.1,
    color: '#00a2ee'
  },
  {
    language: 'Python',
    value: 68.0,
    color: '#fbcb39'
  },
  {
    language: 'TypeScript',
    value: 67.0,
    color: '#007bc8'
  },
  {
    language: 'Go',
    value: 65.6,
    color: '#65cedb'
  },
  {
    language: 'Swift',
    value: 65.1,
    color: '#ff6e52'
  },
  {
    language: 'JavaScript',
    value: 61.9,
    color: '#f9de3f'
  },
  {
    language: 'C#',
    value: 60.4,
    color: '#5d2f8e'
  },
  {
    language: 'F#',
    value: 59.6,
    color: '#008fc9'
  },
  {
    language: 'Clojure',
    value: 59.6,
    color: '#507dca'
  }
];

const margin = 60,
  width = 1000,
  height = 600,
  chartWidth = width - 2 * margin,
  chartHeight = height - 2 * margin

const svg = d3.select('body').append('svg').attr('width', width).attr('height', height)

const chart = svg.append('g').attr('transform', `translate(${margin}, ${margin})`)

//创建y轴比例尺
const yScale = d3.scaleLinear().range([chartHeight, 0]).domain([0, 100])

//生成y轴
chart.append('g').call(d3.axisLeft(yScale))

//创建x轴比例尺,并设置填充内间距为0.5
const xScale = d3.scaleBand().range([0, chartWidth]).domain(sample.map(s => s.language)).padding(0.5)

//直接通过axisBottom生成x轴,由于要显示到底部,所以应计算位置坐标
chart.append('g').attr('transform', `translate(0, ${chartHeight})`).call(d3.axisBottom(xScale))

//绘制柱状图矩形上的文字提示信息
const bondGroups = chart.append('g').selectAll().data(sample).enter().append('text').attr('class', 'label').attr('y', d => yScale(d.value) - 10).attr('x', d => xScale(d.language)).text(d => `$${d.value}%`)

//创建鼠标hover时的区域
const hoverBox = chart.append('g').attr('class', 'hover')

//渲染出柱状图
chart.append('g').selectAll().data(sample).enter().append('rect').attr('class', 'bar').attr('x', d => xScale(d.language)).attr('y', d => yScale(d.value))
  .attr('height', d => chartHeight - yScale(d.value)).attr('width', xScale.bandwidth())
  .on('mouseenter', function (actual, i) {
    //鼠标进入时,透明度降低,并且有扩大的效果,即x坐标向左平移一段距离,并且宽度增大扩大距离的2倍
    d3.select(this).transition().duration(300).attr('opacity', 0.5).attr('x', d => xScale(d.language) - 5).attr('width', xScale.bandwidth() + 10)

    d3.selectAll('.label').attr('opacity', 0)
    //拿到当前鼠标悬浮矩形的y轴值
    const y = yScale(actual.value)

    //划线
    chart.append('line').attr('class', 'limit').attr('x1', 0).attr('y1', y).attr('x2', chartWidth).attr('y2', y).attr('stroke', 'red').attr('stroke-dasharray', '3 6')

    //鼠标hover时,计算值之间的对比,并显示到柱状图矩形上
    hoverBox.selectAll('text').data(sample).enter().append('text').attr('class', 'divergence').attr('x', d => xScale(d.language)).attr('y', d => yScale(d.value) - 10).text((d, idx) => {
      const divergence = (d.value - actual.value).toFixed(1)

      let text = ''
      if (divergence > 0) text += '+'
      text += `${divergence}%`

      return idx === i ? '' : text
    })
  }).on('mouseleave', function () {
    d3.select(this).transition().duration(300).attr('opacity', 1).attr('x', d => xScale(d.language)).attr('width', xScale.bandwidth())

    d3.selectAll('.divergence').remove()
    d3.selectAll('.label').attr('opacity', 1)
    chart.selectAll('.limit').remove()
  })

  //绘制平行的坐标系轴线,其实是将刻度线反向延长
chart.append('g').attr('class', 'grid').call(
  d3.axisLeft().scale(yScale).tickSize(-chartWidth, 0, 0).tickFormat('')
)

//描述文字
chart.append('text').attr('x', -(chartHeight / 2)).attr('y', -margin / 2).attr('transform', 'rotate(-90)').attr('text-anchor', 'middle').text('Love meter (%)')
chart.append('text').attr('x', chartWidth / 2).attr('y', chartHeight + 40).attr('text-anchor', 'middle').text('Languages')
chart.append('text').attr('x', chartWidth / 2).attr('y', -20).attr('text-anchor', 'middle').text('Most loved programming languages in 2018')
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console