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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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

              
                <div id="app">
</div>
              
            
!

CSS

              
                @chartHeight: 50%;

.circleMixin(@radius, @border: 0) {
  width: 2 * @radius;
	height: 2 * @radius;
	-moz-border-radius: @radius;
	-webkit-border-radius: @radius;
	border-radius: @radius;
  margin-left: -@radius;
  margin-top: -@radius;
  border: @border;
}

html, body, #app {
  height: 100%;
  width: 100%;
  position: relative;
  background: #eef2f5;
  font-family: 'Segoe UI', 'Helvetica', sans-serif;
}

#app {
  padding: 50px 15%;
  width: 100%;
}

.ChartkinTablewalker {
  position: relative;
  width: 100%;
  height: 100%;
  
  .chart-area {
    fill-opacity: 0.5;
    stroke-width: 0;
  }
  
  .Graph {
    position: absolute;
    width: 100%;
    height: 60px;
    svg {
      width: 100%;
      height: 100%;
    }
  }
  
  .BrushZoomingChart {
    width: 100%;
    height: 60px;
    position: relative;

    svg {
      width: 100%;
      height: 100%;
      position: absolute;
      
      .brush {
        .selection {
          fill: #fff;
        }
      }
    }
  }
  
  .chart-container {
    position: absolute;
    width: 100%;
    height: ~"calc(50% - 60px)";
    background: white;
  }
  
  &Chart {
    width: 100%;
    height: 100%;
    position: absolute;
    overflow: hidden;

    svg, .chart-dots {
      width: 100%;
      height: 100%;
      position: absolute;
    }

    .chart-area {
      fill-opacity: 0.5;
      stroke-width: 0;
    }
  }
  
  .ChartOverlay {
    position: absolute;
    height: 100%;
    width: 100%;
    
    .column-container {
      width: 100%;
      height: 100%;
      position: relative;
    
      .column {
        background-color: white;
        position: absolute;
        height: 100%;
        opacity: 0;
        transition: opacity 0.3s ease-out;
        
        &.active {
          opacity: 0.7;
        }
      }
    }
      
    .dots-container {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      pointer-events: none;

      .dot {
        .circleMixin(9px, 4px solid white);
        position: absolute;
        opacity: 0;
        transition: opacity 0.3s ease-out;
        background: black;
        
        &.active {
          opacity: 1;
        }
      }
    }
    
  }
  
  .buttons {
    position: absolute;
    top: 50%; 
    text-align: center;
    width: 100%;
    padding-top: 5px;
    
    .btn {
      position: absolute;
      right: -50px;
      &:first-child {
        left: -50px;
      }
    }
  }
  
  
  &Table {
    position: absolute;
    bottom: 34px;
    height: ~"calc(50% - 34px)";
    width: ~"calc(100%)";
    
    background: #eef2f5;
    font-family: 'Segoe UI', 'Helvetica', sans-serif;
    
    .debug {
      background: #4f90ad;
      color: white;
      padding: 10px;
      margin-top: 2em;
      display: none;
    }
    
    .pillars, .animated-columns {
      
      display: flex;
      position: relative;
      width: 100%;

      .pillar {
        transition: all 0.2s;
        overflow: hidden;
        
        &.invis {
          flex-basis: 0 !important;
          opacity: 0.33;
          transition-duration: 0.4s;
        }

        .block {
          padding: 15px;
          background: white;

          &.head {
            background: transparent;
            color: #777;
          }	
        }

        &.block-labels {
          position: absolute;
          right: 100%;
          width: 300px;

          .block {
            padding: 15px 20px;
            text-align: right;
          }
        }

        &.active {
          opacity: 0.8;

          .block {
            outline: none;
            
            &.block-0 span { color: #4f90ad; border: 2px solid #4f90ad; padding: 2px 8px }
            &.block-1 span { color: #69b99c; border: 2px solid #69b99c; padding: 2px 8px }
            
             &.head {
              background: white;
              font-weight: bold;
            }
          }
        }
      }
    }
  }
}
              
            
!

JS

              
                const randomRange = (min, max) => min + Math.random() * (max - min);
const numIntervals = 52;
const data = [
  { 
    name: 'Value 1',
    values: Array.from({length: numIntervals}, d => Math.round(randomRange(500, 1000))),
  },
  { 
    name: 'Value 2', 
    values: Array.from({length: numIntervals}, d => Math.round(randomRange(30, 40) * 10) / 10),
  },
  { 
    name: 'Value 3', 
    values: Array.from({length: numIntervals}, d => Math.round(randomRange(60, 90) * 10) / 10),
  },
  { 
    name: 'Value 4', 
    values: Array.from({length: numIntervals}, d => Math.round(randomRange(60, 90) * 10) / 10),
  },
  { 
    name: 'Value 5', 
    values: Array.from({length: numIntervals}, d => Math.round(randomRange(60, 90) * 10) / 10),
  },
  { 
    name: 'Testdata A', 
    values: Array.from({length: numIntervals}, d => Math.round(randomRange(60, 90) * 10) / 10),
  },
  { 
    name: 'Testdata B', 
    values: Array.from({length: numIntervals}, d => Math.round(randomRange(60, 90) * 10) / 10),
  },
  { 
    name: 'Testdata C', 
    values: Array.from({length: numIntervals}, d => Math.round(randomRange(60, 90) * 10) / 10),
  },
  { 
    name: 'Testdata D', 
    values: Array.from({length: numIntervals}, d => Math.round(randomRange(60, 90) * 10) / 10),
  },
];
const rowLabels = data.map(d => d.name);

// BrushChart /////////////////////

class Graph extends React.Component {
  
  shouldComponentUpdate() {
    return false;
  }
  
  componentWillReceiveProps(nextProps) {
    this.updateChart(nextProps);
  }
  
  componentDidMount() {
    this.updateChart(this.props);
  }
  
  render() {
    return (
      <div className='Graph' ref={el => this.domNode = el}>
        <svg ref={e => this.svg = e}>
          <path className='chart-area' ref={el => this.areaNode = d3.select(el)} />
        </svg>
      </div>
    );
  }
  
  updateChart({ data, curving, graphColor, bounds }) {
    const domainX = [0, data.length - 1];
    const domainY = d3.extent(data, d => d.y).reverse();
    const scaleX = d3.scaleLinear().domain(domainX).range([0, bounds.width]);
    const scaleY = d3.scaleLinear().domain(domainY).range([0, bounds.height]);
    this.renderGraph(data, bounds.height, scaleX, scaleY, curving, graphColor);
  }
  
  renderGraph(data, height, scaleX, scaleY, curving, color) {
    const area = d3.area()
      .curve(curving)
      .x(d => scaleX(d.x))
      .y0(height)
      .y1(d => scaleY(d.y))
    ;
    this.areaNode
      .data([data])
      .attr('d', area)
      .attr('fill', color)
    ;
  }
}

Graph.defaultProps = {
  curving: d3.curveLinear,
  graphColor: 'steelblue',
};

Graph.propTypes = {
  data: React.PropTypes.array.isRequired,
  curving: React.PropTypes.func,
  graphColor: React.PropTypes.string,
};

class BrushChart extends React.Component {
  
  constructor(props) {
    super(props);
    
    this.chartState = {
      selection: props.selection,
      bounds: props.bounds,
      isBrushing: false,
    };
  }
  
  shouldComponentUpdate() {
    return false;
  }
  
  componentWillReceiveProps(nextProps) {
    if (!this.chartState.isBrushing) {
      this.chartState.selection = nextProps.selection;
      this.chartState.bounds = nextProps.bounds;
      this.updateChart(nextProps);
    }
  }
  
  componentDidMount() {
    this.chartState.selection = this.props.selection;
    this.updateChart(this.props);
  }
  
  render() {
    return (
      <div className='BrushZoomingChart' ref={el => this.domNode = el}>
        <svg ref={e => this.svg = e}>
          <g ref={e => this.brush = d3.select(e)} />
        </svg>
      </div>
    );
  }
  
  updateChart({ numDataPoints, curving, graphColor, bounds, selection }) {
    const domainX = [0, numDataPoints];
    const scaleX = d3.scaleLinear().domain(domainX).range([0, bounds.width]);
    this.renderBrush(this.chartState.selection, scaleX);
  }
  
  onBrushed() {
    const { numDataPoints, onSelectionChanged } = this.props;
    const { bounds } = this.chartState;
    const domain = [0, bounds.width];
    const range = [0, numDataPoints];
    const scale = d3.scaleLinear().domain(domain).range(range);
    
    this.chartState.isBrushing = true;
    
    if (d3.event.selection) {
      const selection = d3.event.selection.map(v => Math.round(scale(v)));
      this.updateSelection(selection);
    }
  }
  
  onBrushEnded() {
    this.chartState.isBrushing = false;
    if (this.props.snipping) {
      this.snipToIndex();
    }
  }
  
  snipToIndex() {
    const {numDataPoints} = this.props;
    const {bounds, selection} = this.chartState;
    const scale = d3.scaleLinear().domain([0, numDataPoints]).range([0, bounds.width]);
    this.renderBrush(selection, scale);
  }
  
  updateSelection(selection) {
    if (selection[0] !== this.chartState.selection[0] || selection[1] !== this.chartState.selection[1]) {
      this.props.onSelectionChanged({selection: selection});
      this.chartState.selection = selection;
    }
  }
  
  renderBrush(selection, scale) {
    const range = selection.map(v => scale(v));
    const brush = d3.brushX();
    this.brush
      .attr('class', 'brush')
      .call(brush)
      .call(brush.move, range)
    ;
    // remove resizing handles
    this.brush
      .selectAll('.handle')
      .remove()
    ;
    brush
      .on('start brush', this.onBrushed.bind(this))
      .on('end', this.onBrushEnded.bind(this))
    ;
  }
}

BrushChart.defaultProps = {
  curving: d3.curveLinear,
  graphColor: 'steelblue',
  selection: [0, 0],
  onSelectionChanged: data => undefined,
  snipping: true,
};

BrushChart.propTypes = {
  numDataPoints: React.PropTypes.number.isRequired,
  curving: React.PropTypes.func,
  graphColor: React.PropTypes.string,
  selection: React.PropTypes.arrayOf(React.PropTypes.number),
  onSelectionChanged: React.PropTypes.func,
  snipping: React.PropTypes.bool,
};


// Table //////////////////////////

class CKTW_Table extends React.Component {
	
	constructor(props) {
		super(props);
		this.state = {
			data: [],
		}
	}
	
	renderColumns(data, rowLabels) {
		const columns = [];
    const columnCount = this.props.numCols;
    const columnWidth = this.props.width / columnCount;
    const startIndex = this.props.startIndex;
		const columnStyle = {
			flex: `0 1 ${columnWidth}px`,
		}
		
		columns.push(
			<div className="pillar block-labels">
				<div className="block head empty">&nbsp;</div>
				{ 
					rowLabels.map((label, index) => {
						return (
							<div className="block head">{label}</div>
						)
					}) 
				}
			</div>
		);
		
		const endIndex = columnCount + startIndex;
    
    data.forEach((item, i) => {
      columns.push(
				<CKTW_TableColumn 
					key={i} 
					columnIndex={i} 
          isVisible={i >= startIndex && i < endIndex}
					isActive={this.props.activeColumn == i}
					onActiveChange={this.props.onChangeColumn}
					columnWidth={columnWidth} 
					values={data[i].values} 
					name={data[i].name} 
				/>
			);
    });
    
    return columns;
		
	}
	
	transformDataToColData(data) {
		const columnData = [];
		
		data[0].values.forEach((value, valueIndex) => {
			columnData[valueIndex] = {
				name: `KW${valueIndex + 1}`,
				values: [],
			}
		});

		columnData.forEach((column, columnIndex) => {
			data.forEach((row, rowIndex) => {
				column.values.push(row.values[columnIndex]);
			})
		});
		
		this.setState({
			data: columnData,
		});
	}
	
	componentDidMount() {
		this.transformDataToColData(this.props.data);
	}
	
	render() {
		return (
			<div ref={ el => this.table = el } className="ChartkinTablewalkerTable">
				<div className="table-inner pillars">
					{ this.renderColumns(this.state.data, this.props.rowLabels) }
				</div>
			</div>
		);
	}
}

class CKTW_TableColumn extends React.Component {
	
  componentWillUnmount() {
    console.log(this.props.columnIndex);
  }
  
	renderBlocks(columnData, columnHead) {
		const blocks = [];
		
		const cellStyleHead = {
			textAlign: 'center',
		}
		
		blocks.push(
			<div 
					style={cellStyleHead} 
					className={`block head`}
					key={`block-${i}`}
				>
					{columnHead}
				</div>
		)
		
		// content INNER
		for (var i in columnData) {
			const cellStyle = {
				textAlign: 'center',
			}
			blocks.push(
				<div 
					style={cellStyle} 
					className={`block block-${i} ${this.props.isActive ? 'highlighted' : ''}`}
					key={`block-${i}`}
				>
          <span>{columnData[i]}</span>
				</div>
			)
		}
		return blocks;
	}
	
	render() {
		let columnStyle = {
			flex: `0 1 ${this.props.columnWidth}px`,
		}
		return (
			<div 
				style={columnStyle} 
				className={`pillar ${this.props.columnIndex} ${this.props.isVisible ? '' : 'invis'} ${this.props.isActive ? 'active' : ''}`}
				onMouseEnter={(e) => {
					this.props.onActiveChange({activeColumn: this.props.columnIndex});
				}}
				onMouseLeave={(e) => {
					this.props.onActiveChange({activeColumn: null})
				}}
				key={`pillar-${this.props.columnIndex}`}
			>
				{ this.renderBlocks(this.props.values, this.props.name) } 
			</div>
		);
	}
} 

CKTW_Table.defaultProps = {
	activeColumn: 0,
	data,
	rowLabels,
}


// Chart //////////////////////////

class Chart extends React.Component {
  
  constructor(props) {
    super(props);
    
    this.chartState = {
      isMounted: false,
    };
  }
  
  shouldComponentUpdate() {
    return false;
  }
  
  componentWillReceiveProps(nextProps) {
    this.updateChart(nextProps);
  }
  
  componentDidMount() {
    window.addEventListener('resize', this.onResize.bind(this));
    this.updateChart(this.props);
    this.chartState.isMounted = true;
  }
  
  componentWillUnmount() {
    window.removeEventListener('resize', this.onResize);
  }
  
  render() {
    return (
      <div className='ChartkinTablewalkerChart' ref={el => this.chartNode = el}>
        <svg>
          <path className='chart-area' ref={el => this.areaNode = d3.select(el)} />
          <path className='chart-line' ref={el => this.graphNode = d3.select(el)} />
        </svg>
      </div>
    );
  }
  
  onResize() {
    this.updateChart(this.props);
  }
  
  updateChart({ bounds, data, curving, graphColor, numCols, startIndex }) {
    const domainX = [startIndex, startIndex + data.length - 1];
    const domainY = d3.extent(data, d => d.y).reverse();
    const colWidth = bounds.width / numCols;
    const chartWidth = colWidth * data.length;
    const halfColWidth = colWidth * .5;
    const scaleX = d3.scaleLinear().domain(domainX).range([halfColWidth, chartWidth - halfColWidth]);
    const scaleY = d3.scaleLinear().domain(domainY).range([0, bounds.height]);
    if (this.chartState.isMounted) {
      this.renderGraph(data, bounds.height, scaleX, scaleY, curving, graphColor);
    }
  }
  
  renderGraph(data, height, scaleX, scaleY, curving, color) {
    const area = d3.area()
      .curve(curving)
      .x(d => scaleX(d.x))
      .y0(height)
      .y1(d => scaleY(d.y))
    ;
    this.areaNode.data([data])
      .attr('fill', color)
      .transition()
      .duration(300)
      .ease(d3.easeQuadOut)
      .attr('d', area)
    ;
  }
}

Chart.defaultProps = {
  curving: d3.curveLinear,
  startIndex: 0,
  onChangeColumn: () => undefined,
  activeColumn: -1,
  graphColor: 'steelblue',
};

Chart.propTypes = {
  data: React.PropTypes.array.isRequired,
  numCols: React.PropTypes.number.isRequired,
  bounds: React.PropTypes.object.isRequired,
  curving: React.PropTypes.func,
  startIndex: React.PropTypes.number,
  onChangeColumn: React.func,
  activeColumn: React.number,
  graphColor: React.PropTypes.string,
};


// Chart Overlay ///////////////////

const ChartOverlay = ({ data, numCols, bounds, startIndex, onChangeColumn, activeColumn, colors }) => {
  const colWidth = 100 / numCols;
  const halfColWidth = colWidth * .5;
  const filterVisibleColumns = (d, i) => i >= startIndex && i < startIndex + numCols;
  return (
    <div className='ChartOverlay'>
      <div className='column-container'>
        {
          data[0].values
            .filter(filterVisibleColumns)
            .map((d, i) => (
            <div 
              className={`column ${activeColumn === i + startIndex ? 'active' : ''}`}
              style={{left: `${i * colWidth}%`, width: `${colWidth}%`}} 
              onMouseEnter={onChangeColumn.bind(null, { activeColumn: i + startIndex })}
              onMouseLeave={onChangeColumn.bind(null, { activeColumn: -1 })}
              />
          ))
        }
      </div>
      <div className='dots-container'>
        {
          data.map((row, rowIndex) => (
            row.values.filter(filterVisibleColumns).map((d, i) => {
              const domain = d3.extent(row.values);
              const range = [100, 0];
              const scaleY = d3.scaleLinear().domain(domain).range(range);
              return (
                <span 
                  className={`dot ${activeColumn === i + startIndex ? 'active' : ''}`}
                  style={{
                    left: `${i * colWidth + halfColWidth}%`,
                      top: `${scaleY(d)}%`,
                        backgroundColor: colors[rowIndex],
                  }}
                  />
              );
            })
          ))
        }
      </div>
    </div>
  );
}

ChartOverlay.defaultProps = {
  startIndex: 0,
  onChangeColumn: () => undefined,
  activeColumn: -1,
};

ChartOverlay.propTypes = {
  data: React.PropTypes.array.isRequired,
  minColWidth: React.PropTypes.number.isRequired,
  bounds: React.PropTypes.object.isRequired,
  colors: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  startIndex: React.PropTypes.number,
  onChangeColumn: React.PropTypes.func,
  activeColumn: React.PropTypes.number,
};


//  ChartkinTablewalker ////////////

class ChartkinTablewalker extends React.Component {
  
  constructor(props) {
    super(props); 
    this.state = {
      startIndex: 0,
      activeColumn: -1,
      bounds: { width: 0, height: 0 },
      chartBounds: { width: 0, height: 0 },
    };
  }
  
  componentDidMount() {
    const bounds = this.domNode.getBoundingClientRect();
    const chartBounds = this.chartContainer.getBoundingClientRect();
    this.setState({ bounds, chartBounds });
    window.addEventListener('resize', this.onResize.bind(this));
    window.addEventListener('keydown', (e) => {
      switch(e.keyCode) {
        case 37:
          this.onNavigate(-1);
          break;
        case 39:
          this.onNavigate(1);
          break;
      }
    }, false);
    
    d3.selectAll('.mouse-wheel-horizontal').on('wheel', (...args) => {
      const e = d3.event;
      this.onNavigate(e.deltaY > 0 ? 1 : -1);
      e.stopPropagation();
      e.preventDefault();
      e.cancelBubble = true;
    });
  }
  
  componentWillUnmount() {
    window.removeEventListener('resize', this.onResize);
  }
  
  calculateNumCols(minColWidth, numIntervals) {
    const bounds = this.domNode ? this.domNode.getBoundingClientRect() : { width: 0 };
    const numMinCols = Math.floor(bounds.width / minColWidth);
    return Math.max(0, Math.min(numMinCols, numIntervals));
  }
  
  onNavigate(direction) {
    const { minColWidth, data } = this.props;
    const numIntervals = data[0].values.length;
    const numCols = this.calculateNumCols(minColWidth, numIntervals);
    const startIndex = Math.min(
      numIntervals - numCols,
      Math.max(0, this.state.startIndex + direction)
    );
    this.setState({ startIndex });
  }
  
  onChangeColumn({activeColumn}) {
    this.setState({ activeColumn });
  }
  
  onSelectionChanged({selection}) {
    this.setState({
      startIndex: selection[0],
    });
  }
  
  onResize() {
    const bounds = this.domNode.getBoundingClientRect();
    const chartBounds = this.chartContainer.getBoundingClientRect();
    this.setState({ bounds, chartBounds });
  }
  
  render() {
    const {data, minColWidth, colors, curving} = this.props;
    const {startIndex, activeColumn, bounds, chartBounds } = this.state;
    
    const brushChartBounds = { width: bounds.width, height: 60 };
    const numIntervals = data[0].values.length;
    const numCols = this.calculateNumCols(minColWidth, numIntervals);
    
    const graphData = data.filter((d, i) => i < 2);
    
    return (
      <div className='ChartkinTablewalker' ref={e => this.domNode = e}>
        <div className='brush-chart-container mouse-wheel-horizontal'>
          {
            graphData.map((row, rowIndex) => (
              <Graph 
                data={row.values.map((d, i) => ({x: i, y: d}))}
                curving={curving}
                graphColor={colors[rowIndex]}
                bounds={brushChartBounds}
              />
            ))
          }
          <BrushChart 
            numDataPoints={numIntervals}
            curving={curving}
            graphColor={'steelblue'}
            selection={[startIndex, startIndex + numCols]}
            onSelectionChanged={this.onSelectionChanged.bind(this)}
            bounds={brushChartBounds}
            minColWidth={minColWidth}
          />
        </div>
        <div className='chart-container mouse-wheel-horizontal' ref={e => this.chartContainer = e}>
          {
            graphData.map((row, i) => (
              <Chart 
                data={row.values.map((d, x) => ({x: x, y: d}))}
                curving={curving}
                startIndex={startIndex}
                onChangeColumn={this.onChangeColumn.bind(this)}
                activeColumn={activeColumn}
                graphColor={colors[i]}
                bounds={chartBounds}
                numCols={numCols}
              /> 
            ))
          }
          <ChartOverlay
            data={graphData}
            bounds={chartBounds} 
            startIndex={startIndex}
            onChangeColumn={this.onChangeColumn.bind(this)}
            numCols={numCols}
            activeColumn={activeColumn}
            colors={colors}
          />
        </div>
        <CKTW_Table 
          startIndex={startIndex}
          data={data} 
          rowLabels={rowLabels}
          activeColumn={activeColumn}
          onChangeColumn={this.onChangeColumn.bind(this)}
          numCols={numCols}
          width={bounds.width}
          startIndex={startIndex}
        />
        <div className="buttons">
          <button className="btn btn-default" onClick={this.onNavigate.bind(this, -1)}>&larr;</button>
          &nbsp;
          <button className="btn btn-default" onClick={this.onNavigate.bind(this, 1)}>&rarr;</button>
        </div>
      </div>
    );
  }
  
}

ChartkinTablewalker.propTypes = {
  minColWidth: React.PropTypes.number,
  colors: React.PropTypes.arrayOf(React.PropTypes.string),
  curving: React.PropTypes.func,
};

ChartkinTablewalker.defaultProps = {
  minColWidth: 100,
  colors: ['#4f90ad', '#69b99c', '#993423', '#994499', '#37A4AA', '#63C023'],
  curving: d3.curveCatmullRom,
};


// Integration /////////////////////

ReactDOM.render(<ChartkinTablewalker data={data} curving={d3.curveMonotoneX} />, app);
              
            
!
999px

Console