_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q23400
rewriteDuration
train
function rewriteDuration() { var buffer = new ArrayBufferDataStream(8), oldPos = blobBuffer.pos; // Rewrite the data payload (don't need to update the id or size) buffer.writeDoubleBE(clusterStartTime); // And write that through to the file blobBuffer.seek(segmentDuration.dataOffset); blobBuffer.write(buffer.getAsDataArray()); blobBuffer.seek(oldPos); }
javascript
{ "resource": "" }
q23401
cordovaPathToNative
train
function cordovaPathToNative(path) { var cleanPath = String(path); // turn / into \\ cleanPath = cleanPath.replace(/\//g, '\\'); // turn \\ into \ cleanPath = cleanPath.replace(/\\\\/g, '\\'); // strip end \\ characters cleanPath = cleanPath.replace(/\\+$/g, ''); return cleanPath; }
javascript
{ "resource": "" }
q23402
getMaxLengthLine
train
function getMaxLengthLine(...texts) { let textSizes = texts.filter(x => !!x) .map(x => x.node().getBBox().width); return d3Array.max(textSizes); }
javascript
{ "resource": "" }
q23403
updatePositionAndSize
train
function updatePositionAndSize(mousePosition, parentChartSize) { let [tooltipX, tooltipY] = getTooltipPosition(mousePosition, parentChartSize); svg.transition() .duration(mouseChaseDuration) .ease(ease) .attr('height', chartHeight + margin.top + margin.bottom) .attr('width', chartWidth + margin.left + margin.right) .attr('transform', `translate(${tooltipX},${tooltipY})`); tooltipBackground .attr('height', chartHeight + margin.top + margin.bottom) .attr('width', chartWidth + margin.left + margin.right); }
javascript
{ "resource": "" }
q23404
cleanData
train
function cleanData(originalData) { return originalData.reduce((acc, d) => { d.value = +d[valueLabel]; d.key = String(d[nameLabel]); return [...acc, d]; }, []); }
javascript
{ "resource": "" }
q23405
drawSteps
train
function drawSteps(){ let steps = svg.select('.chart-group').selectAll('.step').data(data); // Enter steps.enter() .append('rect') .classed('step', true) .attr('x', chartWidth) // Initially drawing the steps at the end of Y axis .attr('y', ({value}) => yScale(value)) .attr('width', xScale.bandwidth()) .attr('height', (d) => (chartHeight - yScale(d.value))) .on('mouseover', function(d) { handleMouseOver(this, d, chartWidth, chartHeight); }) .on('mousemove', function(d) { handleMouseMove(this, d, chartWidth, chartHeight); }) .on('mouseout', function(d) { handleMouseOut(this, d, chartWidth, chartHeight); }) .merge(steps) .transition() .ease(ease) .attr('x', ({key}) => xScale(key)) .attr('y', function(d) { return yScale(d.value); }) .attr('width', xScale.bandwidth()) .attr('height', function(d) { return chartHeight - yScale(d.value); }); // Exit steps.exit() .transition() .style('opacity', 0) .remove(); }
javascript
{ "resource": "" }
q23406
buildAxis
train
function buildAxis(){ let minor, major; if (xAxisFormat === 'custom' && typeof xAxisCustomFormat === 'string') { minor = { tick: xTicks, format: d3TimeFormat.timeFormat(xAxisCustomFormat) }; } else { ({minor, major} = timeAxisHelper.getTimeSeriesAxis(data, width, xAxisFormat)); } xAxis = d3Axis.axisBottom(xScale) .ticks(minor.tick) .tickSize(10, 0) .tickPadding([tickPadding]) .tickFormat(minor.format); }
javascript
{ "resource": "" }
q23407
buildBrush
train
function buildBrush() { brush = d3Brush.brushX() .extent([[0, 0], [chartWidth, chartHeight]]) .on('brush', handleBrushStart) .on('end', handleBrushEnd); }
javascript
{ "resource": "" }
q23408
buildGradient
train
function buildGradient() { if (!chartGradientEl) { chartGradientEl = svg.select('.metadata-group') .append('linearGradient') .attr('id', gradientId) .attr('gradientUnits', 'userSpaceOnUse') .attr('x1', 0) .attr('x2', xScale(data[data.length - 1].date)) .attr('y1', 0) .attr('y2', 0) .selectAll('stop') .data([ {offset: '0%', color: gradient[0]}, {offset: '100%', color: gradient[1]} ]) .enter().append('stop') .attr('offset', ({offset}) => offset) .attr('stop-color', ({color}) => color); } }
javascript
{ "resource": "" }
q23409
drawArea
train
function drawArea() { if (brushArea) { svg.selectAll('.brush-area').remove(); } // Create and configure the area generator brushArea = d3Shape.area() .x(({date}) => xScale(date)) .y0(chartHeight) .y1(({value}) => yScale(value)) .curve(d3Shape.curveBasis); // Create the area path svg.select('.chart-group') .append('path') .datum(data) .attr('class', 'brush-area') .attr('d', brushArea); }
javascript
{ "resource": "" }
q23410
drawBrush
train
function drawBrush() { chartBrush = svg.select('.brush-group') .call(brush); // Update the height of the brushing rectangle chartBrush.selectAll('rect') .classed('brush-rect', true) .attr('height', chartHeight); chartBrush.selectAll('.selection') .attr('fill', `url(#${gradientId})`); }
javascript
{ "resource": "" }
q23411
drawHandles
train
function drawHandles() { let handleFillColor = colorHelper.colorSchemasHuman.grey[1]; // Styling handle = chartBrush .selectAll('.handle.brush-rect') .style('fill', handleFillColor); }
javascript
{ "resource": "" }
q23412
handleBrushStart
train
function handleBrushStart() { const selection = d3Selection.event.selection; if (!selection) { return; } dispatcher.call('customBrushStart', this, selection.map(xScale.invert)); }
javascript
{ "resource": "" }
q23413
setBrushByDates
train
function setBrushByDates(dateA, dateB) { let selection = null; if (dateA !== null) { selection = [ xScale(new Date(dateA)), xScale(new Date(dateB)) ]; } brush.move(chartBrush, selection); }
javascript
{ "resource": "" }
q23414
createGradients
train
function createGradients() { let metadataGroup = svg.select('.metadata-group'); if (areaGradientEl || lineGradientEl) { svg.selectAll(`#${areaGradientId}`).remove(); svg.selectAll(`#${lineGradientId}`).remove(); } areaGradientEl = metadataGroup.append('linearGradient') .attr('id', areaGradientId) .attr('class', 'area-gradient') .attr('gradientUnits', 'userSpaceOnUse') .attr('x1', 0) .attr('x2', xScale(data[data.length - 1].date)) .attr('y1', 0) .attr('y2', 0) .selectAll('stop') .data([ {offset: '0%', color: areaGradient[0]}, {offset: '100%', color: areaGradient[1]} ]) .enter().append('stop') .attr('offset', ({offset}) => offset) .attr('stop-color', ({color}) => color); lineGradientEl = metadataGroup.append('linearGradient') .attr('id', lineGradientId) .attr('class', 'line-gradient') .attr('gradientUnits', 'userSpaceOnUse') .attr('x1', 0) .attr('x2', xScale(data[data.length - 1].date)) .attr('y1', 0) .attr('y2', 0) .selectAll('stop') .data([ {offset: '0%', color: lineGradient[0]}, {offset: '100%', color: lineGradient[1]} ]) .enter().append('stop') .attr('offset', ({offset}) => offset) .attr('stop-color', ({color}) => color); }
javascript
{ "resource": "" }
q23415
drawArea
train
function drawArea(){ if (area) { svg.selectAll('.sparkline-area').remove(); } area = d3Shape.area() .x(({date}) => xScale(date)) .y0(() => yScale(0) + lineStrokeWidth / 2) .y1(({value}) => yScale(value)) .curve(d3Shape.curveBasis); svg.select('.chart-group') .append('path') .datum(data) .attr('class', 'sparkline-area') .attr('fill', `url(#${areaGradientId})`) .attr('d', area) .attr('clip-path', `url(#${maskingClipId})`); }
javascript
{ "resource": "" }
q23416
drawLine
train
function drawLine(){ if (topLine) { svg.selectAll('.line').remove(); } topLine = d3Shape.line() .curve(d3Shape.curveBasis) .x(({date}) => xScale(date)) .y(({value}) => yScale(value)); svg.select('.chart-group') .append('path') .datum(data) .attr('class', 'line') .attr('stroke', `url(#${lineGradientId})`) .attr('d', topLine) .attr('clip-path', `url(#${maskingClipId})`); }
javascript
{ "resource": "" }
q23417
drawSparklineTitle
train
function drawSparklineTitle() { if (titleEl) { svg.selectAll('.sparkline-text').remove(); } titleEl = svg.selectAll('.text-group') .append('text') .attr('x', chartWidth / 2) .attr('y', chartHeight / 6) .attr('text-anchor', 'middle') .attr('class', 'sparkline-text') .style('font-size', titleTextStyle['font-size'] || DEFAULT_TITLE_TEXT_STYLE['font-size']) .style('fill', titleTextStyle['fill'] || lineGradient[0]) .style('font-family', titleTextStyle['font-family'] || DEFAULT_TITLE_TEXT_STYLE['font-family']) .style('font-weight', titleTextStyle['font-weight'] || DEFAULT_TITLE_TEXT_STYLE['font-weight']) .style('font-style', titleTextStyle['font-style'] || DEFAULT_TITLE_TEXT_STYLE['font-style']) .text(titleText) }
javascript
{ "resource": "" }
q23418
drawEndMarker
train
function drawEndMarker(){ if (circle) { svg.selectAll('.sparkline-circle').remove(); } circle = svg.selectAll('.chart-group') .append('circle') .attr('class', 'sparkline-circle') .attr('cx', xScale(data[data.length - 1].date)) .attr('cy', yScale(data[data.length - 1].value)) .attr('r', markerSize); }
javascript
{ "resource": "" }
q23419
main
train
function main() { loadDependencies(); setInitialData(); domHelpers.initDomElements(); setDataInInputField(); setConfigInInputField(); setChartSelectorType(); setNewChart(); setHandlers(); }
javascript
{ "resource": "" }
q23420
setHandlers
train
function setHandlers() { d3.select(`.${chartSelectorClass}`).on('change', _handleChartSelectorChange); d3.select(`.${dataSelectorClass}`).on('change', _handleDataSelectorChange); d3.select(`.${dataSubmitButtonClass}`).on('click', _handleDataUpdate); d3.select(`.${dataResetButtonClass}`).on('click', _handleDataReset); d3.select(`.${dataInputSizeToggleClass}`).on('click', _handleDataSizeToggle); d3.select(`.${configSubmitButtonClass}`).on('click', _handleConfigUpdate); d3.select(`.${configResetButtonClass}`).on('click', _handleConfigReset); d3.select(`.${configAddTooltipClass}`).on('click', _handleAddTooltip.bind(null, tooltipTypes.basic)) d3.select(`.${configAddMiniTooltipClass}`).on('click', _handleAddTooltip.bind(null, tooltipTypes.mini)) }
javascript
{ "resource": "" }
q23421
setNewDataTypes
train
function setNewDataTypes() { let chartType = getCurrentType(); let dataTypes = Object.keys(defaultData[chartType]); let dataSelector = d3.select(`.${dataSelectorClass}`) .selectAll('option') .data(dataTypes); dataSelector.enter().append('option') .merge(dataSelector) .attr('value', (d) => d) .text((d) => d); dataSelector.exit().remove(); }
javascript
{ "resource": "" }
q23422
getCurrentData
train
function getCurrentData() { let currentData = storage.getDataByKey(savedDataKey); if (!currentData) { let chartType = getCurrentType(); let {initialDataType} = defaultConfig[chartType]; currentData = defaultData[chartType][initialDataType]; storage.setDataByKey(savedDataKey, currentData); } return currentData; }
javascript
{ "resource": "" }
q23423
getCurrentConfig
train
function getCurrentConfig() { let initString = storage.getDataByKey(savedConfigKey); if (!initString) { let chartType = getCurrentType(); let {chartConfig} = defaultConfig[chartType]; initString = formatParamsIntoChartInitString(chartConfig); storage.setDataByKey(savedConfigKey, initString); } return initString; }
javascript
{ "resource": "" }
q23424
getCurrentType
train
function getCurrentType() { let currentType = storage.getDataByKey(savedChartTypeKey); if (!currentType) { currentType = charts[0]; storage.setDataByKey(savedChartTypeKey, currentType); } return currentType; }
javascript
{ "resource": "" }
q23425
_handleAddTooltip
train
function _handleAddTooltip(tooltipType) { let initString = getCurrentConfig(); let tooltipInitString = tooltipConfigs[tooltipType].initString; initString = initString.concat(tooltipInitString); configEditor.setValue(prettifyInitString(initString)); setNewChart(); }
javascript
{ "resource": "" }
q23426
_handleDataSelectorChange
train
function _handleDataSelectorChange () { let chartType = getCurrentType(); let dataType = d3.select(`.${dataSelectorClass}`).property('value'); let currentData = defaultData[chartType][dataType]; storage.setDataByKey(savedDataKey, currentData); updateAllComponents(); }
javascript
{ "resource": "" }
q23427
_handleDataUpdate
train
function _handleDataUpdate() { const rawData = dataEditor.getValue(); let freshData = null; try { freshData = evalDataString(rawData); } catch(e) { errors.push(new Error('Could not parse the data from the input field', rawData)); } storage.setDataByKey(savedDataKey, freshData); if (freshData) { setNewChart(); } }
javascript
{ "resource": "" }
q23428
_handleDataReset
train
function _handleDataReset() { storage.removeDataByKey(savedDataKey); let data = getCurrentData(); dataEditor.setValue(prettifyJson(data)); }
javascript
{ "resource": "" }
q23429
_handleConfigReset
train
function _handleConfigReset() { storage.removeDataByKey(savedConfigKey); let initString = getCurrentConfig(); configEditor.setValue(prettifyInitString(initString)); }
javascript
{ "resource": "" }
q23430
_handleChartSelectorChange
train
function _handleChartSelectorChange() { storage.clear(); let chartType = d3.select(`.${chartSelectorClass}`).property('value'); storage.setDataByKey(savedChartTypeKey, chartType); updateAllComponents(); }
javascript
{ "resource": "" }
q23431
_safeLoadDependency
train
function _safeLoadDependency(name) { try { window[name.split('/').pop()] = require(`../src/charts/${name}`); } catch(e) { errors.push({ error: e, filePath: name }); } }
javascript
{ "resource": "" }
q23432
buildAxis
train
function buildAxis() { xAxis = d3Axis.axisBottom(xScale) .ticks(xTicks) .tickPadding(tickPadding) .tickFormat(d3Format.format(xAxisFormat)); yAxis = d3Axis.axisLeft(yScale) .ticks(yTicks) .tickPadding(tickPadding) .tickFormat(d3Format.format(yAxisFormat)); }
javascript
{ "resource": "" }
q23433
buildVoronoi
train
function buildVoronoi() { voronoi = d3Voronoi.voronoi() .x((d) => xScale(d.x)) .y((d) => yScale(d.y)) .extent([ [0, 0], [chartWidth, chartHeight] ])(dataPoints); }
javascript
{ "resource": "" }
q23434
buildScales
train
function buildScales() { const [minX, minY] = [d3Array.min(dataPoints, ({ x }) => x), d3Array.min(dataPoints, ({ y }) => y)]; const [maxX, maxY] = [d3Array.max(dataPoints, ({ x }) => x), d3Array.max(dataPoints, ({ y }) => y)]; const yScaleBottomValue = Math.abs(minY) < 0 ? Math.abs(minY) : 0; xScale = d3Scale.scaleLinear() .domain([minX, maxX]) .rangeRound([0, chartWidth]) .nice(); yScale = d3Scale.scaleLinear() .domain([yScaleBottomValue, maxY]) .rangeRound([chartHeight, 0]) .nice(); colorScale = d3Scale.scaleOrdinal() .domain(dataPoints.map(getName)) .range(colorSchema); areaScale = d3Scale.scaleSqrt() .domain([yScaleBottomValue, maxY]) .range([0, maxCircleArea]); const colorRange = colorScale.range(); /** * Maps data point category name to * each color of the given color scheme * { * name1: 'color1', * name2: 'color2', * name3: 'color3', * ... * } * @private */ nameColorMap = colorScale.domain().reduce((accum, item, i) => { accum[item] = colorRange[i]; return accum; }, {}); }
javascript
{ "resource": "" }
q23435
cleanData
train
function cleanData(originalData) { return originalData.reduce((acc, d) => { d.name = String(d[nameKey]); d.x = d[xKey]; d.y = d[yKey]; return [...acc, d]; }, []); }
javascript
{ "resource": "" }
q23436
drawAxisLabels
train
function drawAxisLabels() { // If y-axis label is given, draw it if (yAxisLabel) { if (yAxisLabelEl) { svg.selectAll('.y-axis-label-text').remove(); } yAxisLabelEl = svg.select('.axis-labels-group') .append('g') .attr('class', 'y-axis-label') .append('text') .classed('y-axis-label-text', true) .attr('x', -chartHeight / 2) .attr('y', yAxisLabelOffset - xAxisPadding.left) .attr('text-anchor', 'middle') .attr('transform', 'rotate(270 0 0)') .text(yAxisLabel) } // If x-axis label is given, draw it if (xAxisLabel) { if (xAxisLabelEl) { svg.selectAll('.x-axis-label-text').remove(); } xAxisLabelEl = svg.selectAll('.axis-labels-group') .append('g') .attr('class', 'x-axis-label') .append('text') .classed('x-axis-label-text', true) .attr('x', chartWidth / 2) .attr('y', chartHeight - xAxisLabelOffset) .attr('text-anchor', 'middle') .text(xAxisLabel); } }
javascript
{ "resource": "" }
q23437
drawTrendline
train
function drawTrendline(linearData) { if (trendLinePath) { trendLinePath.remove(); } const params = [ {x: linearData.x1, y: linearData.y1}, {x: linearData.x2, y: linearData.y2} ]; let line = d3Shape.line() .curve(trendLineCurve) .x(({x}) => xScale(x)) .y(({y}) => yScale(y)); trendLinePath = svg.selectAll('.chart-group') .append('path') .attr('class', 'scatter-trendline') .attr('d', line(params)) .attr('stroke', colorSchema[0]) .attr('stroke-width', trendLineStrokWidth) .attr('fill', 'none'); const totalLength = trendLinePath.node().getTotalLength(); trendLinePath .attr('stroke-dasharray', `${totalLength} ${totalLength}`) .attr('stroke-dashoffset', totalLength) .transition() .delay(trendLineDelay) .duration(trendLineDuration) .ease(ease) .attr('stroke-dashoffset', 0); }
javascript
{ "resource": "" }
q23438
drawVerticalGridLines
train
function drawVerticalGridLines() { maskGridLines = svg.select('.grid-lines-group') .selectAll('line.vertical-grid-line') .data(xScale.ticks(xTicks)) .enter() .append('line') .attr('class', 'vertical-grid-line') .attr('y1', (xAxisPadding.left)) .attr('y2', chartHeight) .attr('x1', (d) => xScale(d)) .attr('x2', (d) => xScale(d)); }
javascript
{ "resource": "" }
q23439
drawDataPoints
train
function drawDataPoints() { let circles = svg.select('.chart-group') .attr('clip-path', `url(#${maskingRectangleId})`) .selectAll('circle') .data(dataPoints) .enter(); if (isAnimated) { circles .append('circle') .attr('class', 'data-point data-point-highlighter') .transition() .delay(delay) .duration(duration) .ease(ease) .style('stroke', (d) => nameColorMap[d.name]) .attr('fill', (d) => ( hasHollowCircles ? hollowColor : nameColorMap[d.name] )) .attr('fill-opacity', circleOpacity) .attr('r', (d) => areaScale(d.y)) .attr('cx', (d) => xScale(d.x)) .attr('cy', (d) => yScale(d.y)) .style('cursor', 'pointer'); } else { circles .append('circle') .attr('class', 'point') .attr('class', 'data-point-highlighter') .style('stroke', (d) => nameColorMap[d.name]) .attr('fill', (d) => ( hasHollowCircles ? hollowColor : nameColorMap[d.name] )) .attr('fill-opacity', circleOpacity) .attr('r', (d) => areaScale(d.y)) .attr('cx', (d) => xScale(d.x)) .attr('cy', (d) => yScale(d.y)) .style('cursor', 'pointer'); } }
javascript
{ "resource": "" }
q23440
drawDataPointsValueHighlights
train
function drawDataPointsValueHighlights(data) { showCrossHairComponentsWithLabels(true); // Draw line perpendicular to y-axis highlightCrossHairContainer.selectAll('line.highlight-y-line') .attr('stroke', nameColorMap[data.name]) .attr('class', 'highlight-y-line') .attr('x1', (xScale(data.x) - areaScale(data.y))) .attr('x2', 0) .attr('y1', yScale(data.y)) .attr('y2', yScale(data.y)); // Draw line perpendicular to x-axis highlightCrossHairContainer.selectAll('line.highlight-x-line') .attr('stroke', nameColorMap[data.name]) .attr('class', 'highlight-x-line') .attr('x1', xScale(data.x)) .attr('x2', xScale(data.x)) .attr('y1', (yScale(data.y) + areaScale(data.y))) .attr('y2', chartHeight); // Draw data label for y value highlightCrossHairLabelsContainer.selectAll('text.highlight-y-legend') .attr('text-anchor', 'middle') .attr('fill', nameColorMap[data.name]) .attr('class', 'highlight-y-legend') .attr('y', (yScale(data.y) + (areaScale(data.y) / 2))) .attr('x', highlightTextLegendOffset) .text(`${d3Format.format(yAxisFormat)(data.y)}`); // Draw data label for x value highlightCrossHairLabelsContainer.selectAll('text.highlight-x-legend') .attr('text-anchor', 'middle') .attr('fill', nameColorMap[data.name]) .attr('class', 'highlight-x-legend') .attr('transform', `translate(0, ${chartHeight - highlightTextLegendOffset})`) .attr('x', (xScale(data.x) - (areaScale(data.y) / 2))) .text(`${d3Format.format(xAxisFormat)(data.x)}`); }
javascript
{ "resource": "" }
q23441
drawHorizontalGridLines
train
function drawHorizontalGridLines() { maskGridLines = svg.select('.grid-lines-group') .selectAll('line.horizontal-grid-line') .data(yScale.ticks(yTicks)) .enter() .append('line') .attr('class', 'horizontal-grid-line') .attr('x1', xAxisPadding.left) .attr('x2', chartWidth) .attr('y1', (d) => yScale(d)) .attr('y2', (d) => yScale(d)); }
javascript
{ "resource": "" }
q23442
calcLinearRegression
train
function calcLinearRegression() { let n = dataPoints.length, x = 0, y = 0, xy = 0, x2 = 0, y2 = 0; dataPoints.forEach(d => { x += d.x; y += d.y; xy += d.x * d.y; x2 += d.x * d.x; y2 += d.y * d.y; }); const denominator = (n * x2) - (x * x); const intercept = ((y * x2) - (x * xy)) / denominator; const slope = ((n * xy) - (x * y)) / denominator; const minX = d3Array.min(dataPoints, ({ x }) => x); const maxX = d3Array.max(dataPoints, ({ x }) => x); return { x1: minX, y1: slope * n + intercept, x2: maxX, y2: slope * maxX + intercept } }
javascript
{ "resource": "" }
q23443
getPointProps
train
function getPointProps(svg) { let mousePos = d3Selection.mouse(svg); mousePos[0] -= margin.left; mousePos[1] -= margin.top; return { closestPoint: voronoi.find(mousePos[0], mousePos[1]), mousePos }; }
javascript
{ "resource": "" }
q23444
handleMouseMove
train
function handleMouseMove(e) { let { mousePos, closestPoint } = getPointProps(e); let pointData = getPointData(closestPoint); if (hasCrossHairs) { drawDataPointsValueHighlights(pointData); } highlightDataPoint(pointData); dispatcher.call('customMouseMove', e, pointData, d3Selection.mouse(e), [chartWidth, chartHeight]); }
javascript
{ "resource": "" }
q23445
handleMouseOver
train
function handleMouseOver (e, d) { dispatcher.call('customMouseOver', e, d, d3Selection.mouse(e)); }
javascript
{ "resource": "" }
q23446
handleMouseOut
train
function handleMouseOut(e, d) { removePointHighlight(); if (hasCrossHairs) { showCrossHairComponentsWithLabels(false); } dispatcher.call('customMouseOut', e, d, d3Selection.mouse(e)); }
javascript
{ "resource": "" }
q23447
handleClick
train
function handleClick(e) { let { closestPoint } = getPointProps(e); let d = getPointData(closestPoint); handleClickAnimation(d); dispatcher.call('customClick', e, d, d3Selection.mouse(e), [chartWidth, chartHeight]); }
javascript
{ "resource": "" }
q23448
handleClickAnimation
train
function handleClickAnimation(dataPoint) { bounceCircleHighlight( highlightCircle, ease, areaScale(dataPoint.y), areaScale(dataPoint.y * 2) ); }
javascript
{ "resource": "" }
q23449
highlightDataPoint
train
function highlightDataPoint(data) { removePointHighlight(); if (!highlightFilter) { highlightFilter = createFilterContainer(svg.select('.metadata-group')); highlightFilterId = createGlowWithMatrix(highlightFilter); } highlightCircle .attr('opacity', 1) .attr('stroke', () => nameColorMap[data.name]) .attr('fill', () => nameColorMap[data.name]) .attr('fill-opacity', circleOpacity) .attr('cx', () => xScale(data.x)) .attr('cy', () => yScale(data.y)) .attr('r', () => areaScale(data.y)) .style('stroke-width', highlightStrokeWidth) .style('stroke-opacity', highlightCircleOpacity); // apply glow container overlay highlightCircle .attr('filter', `url(#${highlightFilterId})`); }
javascript
{ "resource": "" }
q23450
initHighlightComponents
train
function initHighlightComponents() { highlightCircle = svg.select('.metadata-group') .selectAll('circle.highlight-circle') .data([1]) .enter() .append('circle') .attr('class', 'highlight-circle') .attr('cursor', 'pointer'); if (hasCrossHairs) { // initialize cross hair lines container highlightCrossHairContainer = svg.select('.chart-group') .append('g') .attr('class', 'crosshair-lines-container'); // initialize corss hair labels container highlightCrossHairLabelsContainer = svg.select('.metadata-group') .append('g') .attr('class', 'crosshair-labels-container'); highlightCrossHairContainer.selectAll('line.highlight-y-line') .data([1]) .enter() .append('line') .attr('class', 'highlight-y-line'); highlightCrossHairContainer.selectAll('line.highlight-x-line') .data([1]) .enter() .append('line') .attr('class', 'highlight-x-line'); highlightCrossHairLabelsContainer.selectAll('text.highlight-y-legend') .data([1]) .enter() .append('text') .attr('class', 'highlight-y-legend'); highlightCrossHairLabelsContainer.selectAll('text.highlight-x-legend') .data([1]) .enter() .append('text') .attr('class', 'highlight-x-legend'); } }
javascript
{ "resource": "" }
q23451
showCrossHairComponentsWithLabels
train
function showCrossHairComponentsWithLabels(status = false) { const opacityIndex = status ? 1 : 0; highlightCrossHairContainer.attr('opacity', opacityIndex); highlightCrossHairLabelsContainer.attr('opacity', opacityIndex); }
javascript
{ "resource": "" }
q23452
exportChart
train
function exportChart(d3svg, filename, title) { if (isIE) { console.error(IE_ERROR_MSG); return false; } let img = createImage(convertSvgToHtml.call(this, d3svg, title)); img.onload = handleImageLoad.bind( img, createCanvas(this.width(), this.height()), filename ); }
javascript
{ "resource": "" }
q23453
convertSvgToHtml
train
function convertSvgToHtml (d3svg, title) { if (!d3svg) { return; } d3svg.attr('version', 1.1) .attr('xmlns', 'http://www.w3.org/2000/svg'); let serializer = serializeWithStyles.initializeSerializer(); let html = serializer(d3svg.node()); html = formatHtmlByBrowser(html); html = prependTitle.call(this, html, title, parseInt(d3svg.attr('width'), 10)); html = addBackground(html); return html; }
javascript
{ "resource": "" }
q23454
handleImageLoad
train
function handleImageLoad(canvas, filename, e) { e.preventDefault(); downloadCanvas(drawImageOnCanvas(this, canvas), filename); }
javascript
{ "resource": "" }
q23455
prependTitle
train
function prependTitle(html, title, svgWidth) { if (!title || !svgWidth) { return html; } let {grey} = colorSchemas; html = html.replace(/<g/,`<text x="${this.margin().left}" y="${config.titleTopOffset}" font-family="${config.titleFontFamily}" font-size="${config.titleFontSize}" fill="${grey[6]}"> ${title} </text><g `); return html; }
javascript
{ "resource": "" }
q23456
buildContainerGroups
train
function buildContainerGroups() { let container = svg .append('g') .classed('container-group', true); container .append('g') .classed('chart-group', true); container .append('g') .classed('legend-group', true); }
javascript
{ "resource": "" }
q23457
buildLayout
train
function buildLayout() { layout = d3Shape.pie() .padAngle(paddingAngle) .value(getQuantity) .sort(orderingFunction); }
javascript
{ "resource": "" }
q23458
cleanData
train
function cleanData(data) { let dataWithPercentages; let cleanData = data.reduce((acc, d) => { // Skip data without quantity if (d[quantityLabel] === undefined || d[quantityLabel] === null) { return acc; } d.quantity = +d[quantityLabel]; d.name = String(d[nameLabel]); d.percentage = d[percentageLabel] || null; return [...acc, d]; }, []); let totalQuantity = sumValues(cleanData); if (totalQuantity === 0 && emptyDataConfig.showEmptySlice) { isEmpty = true; } dataWithPercentages = cleanData.map((d) => { d.percentage = String(d.percentage || calculatePercent(d[quantityLabel], totalQuantity, percentageFormat)); return d; }); return dataWithPercentages; }
javascript
{ "resource": "" }
q23459
drawEmptySlice
train
function drawEmptySlice() { if (slices) { svg.selectAll('g.arc').remove(); } slices = svg.select('.chart-group') .selectAll('g.arc') .data(layout(emptyDonutData)); let newSlices = slices.enter() .append('g') .each(storeAngle) .each(reduceOuterRadius) .classed('arc', true) .append('path'); newSlices.merge(slices) .attr('fill', emptyDataConfig.emptySliceColor) .attr('d', shape) .transition() .ease(ease) .duration(pieDrawingTransitionDuration) .attrTween('d', tweenLoading); slices.exit().remove(); }
javascript
{ "resource": "" }
q23460
drawLegend
train
function drawLegend(obj) { if (obj.data) { svg.select('.donut-text') .text(() => centeredTextFunction(obj.data)) .attr('dy', '.2em') .attr('text-anchor', 'middle'); svg.select('.donut-text').call(wrapText, legendWidth); } }
javascript
{ "resource": "" }
q23461
drawSlices
train
function drawSlices() { // Not ideal, we need to figure out how to call exit for nested elements if (slices) { svg.selectAll('g.arc').remove(); } slices = svg.select('.chart-group') .selectAll('g.arc') .data(layout(data)); let newSlices = slices.enter() .append('g') .each(storeAngle) .each(reduceOuterRadius) .classed('arc', true) .append('path'); if (isAnimated) { newSlices.merge(slices) .attr('fill', getSliceFill) .on('mouseover', function(d) { handleMouseOver(this, d, chartWidth, chartHeight); }) .on('mousemove', function(d) { handleMouseMove(this, d, chartWidth, chartHeight); }) .on('mouseout', function(d) { handleMouseOut(this, d, chartWidth, chartHeight); }) .on('click', function(d) { handleClick(this, d, chartWidth, chartHeight); }) .transition() .ease(ease) .duration(pieDrawingTransitionDuration) .attrTween('d', tweenLoading); } else { newSlices.merge(slices) .attr('fill', getSliceFill) .attr('d', shape) .on('mouseover', function(d) { handleMouseOver(this, d, chartWidth, chartHeight); }) .on('mousemove', function(d) { handleMouseMove(this, d, chartWidth, chartHeight); }) .on('mouseout', function(d) { handleMouseOut(this, d, chartWidth, chartHeight); }) .on('click', function(d) { handleClick(this, d, chartWidth, chartHeight); }); } slices.exit().remove(); }
javascript
{ "resource": "" }
q23462
handleMouseOver
train
function handleMouseOver(el, d, chartWidth, chartHeight) { drawLegend(d); dispatcher.call('customMouseOver', el, d, d3Selection.mouse(el), [chartWidth, chartHeight]); if (hasHoverAnimation) { // if the hovered slice is not the same as the last slice hovered // after mouseout event, then shrink the last slice that was highlighted if (lastHighlightedSlice && el !== lastHighlightedSlice) { tweenGrowth(lastHighlightedSlice, externalRadius - radiusHoverOffset, pieHoverTransitionDuration); } if (highlightedSlice && el !== highlightedSlice) { tweenGrowth(highlightedSlice, externalRadius - radiusHoverOffset); } tweenGrowth(el, externalRadius); } }
javascript
{ "resource": "" }
q23463
handleMouseMove
train
function handleMouseMove(el, d, chartWidth, chartHeight) { dispatcher.call('customMouseMove', el, d, d3Selection.mouse(el), [chartWidth, chartHeight]); }
javascript
{ "resource": "" }
q23464
handleMouseOut
train
function handleMouseOut(el, d, chartWidth, chartHeight) { cleanLegend(); // When there is a fixed highlighted slice, // we will always highlight it and render legend if (highlightedSlice && hasFixedHighlightedSlice && !hasLastHoverSliceHighlighted) { drawLegend(highlightedSlice.__data__); tweenGrowth(highlightedSlice, externalRadius); } // When the current slice is not the highlighted, or there isn't a fixed highlighted slice and it is the highlighted // we will shrink the slice if (el !== highlightedSlice || (!hasFixedHighlightedSlice && el === highlightedSlice) ) { tweenGrowth(el, externalRadius - radiusHoverOffset, pieHoverTransitionDuration); } if (hasLastHoverSliceHighlighted) { drawLegend(el.__data__); tweenGrowth(el, externalRadius); lastHighlightedSlice = el; } dispatcher.call('customMouseOut', el, d, d3Selection.mouse(el), [chartWidth, chartHeight]); }
javascript
{ "resource": "" }
q23465
initHighlightSlice
train
function initHighlightSlice() { highlightedSlice = svg.selectAll('.chart-group .arc path') .select(filterHighlightedSlice).node(); if (highlightedSlice) { drawLegend(highlightedSlice.__data__); tweenGrowth(highlightedSlice, externalRadius, pieDrawingTransitionDuration); } }
javascript
{ "resource": "" }
q23466
tweenGrowth
train
function tweenGrowth(slice, outerRadius, delay = 0) { d3Selection.select(slice) .transition() .delay(delay) .attrTween('d', function(d) { let i = d3Interpolate.interpolate(d.outerRadius, outerRadius); return (t) => { d.outerRadius = i(t); return shape(d); }; }); }
javascript
{ "resource": "" }
q23467
wrapText
train
function wrapText(text, legendWidth) { let fontSize = externalRadius / 5; textHelper.wrapText.call(null, 0, fontSize, legendWidth, text.node()); }
javascript
{ "resource": "" }
q23468
getValueText
train
function getValueText(data) { let value = data[valueLabel]; let valueText; if (data.missingValue) { valueText = '-'; } else { valueText = getFormattedValue(value).toString(); } return valueText; }
javascript
{ "resource": "" }
q23469
updateTitle
train
function updateTitle(dataPoint) { let tTitle = title; let formattedDate = formatDate(new Date(dataPoint[dateLabel])); if (tTitle.length) { if (shouldShowDateInTitle) { tTitle = `${tTitle} - ${formattedDate}`; } } else { tTitle = formattedDate; } tooltipTitle.text(tTitle); }
javascript
{ "resource": "" }
q23470
formatDate
train
function formatDate(date) { let settings = dateFormat || defaultAxisSettings; let format = null; let localeOptions = {month:'short', day:'numeric'}; if (settings === axisTimeCombinations.DAY_MONTH || settings === axisTimeCombinations.MONTH_YEAR) { format = monthDayYearFormat; localeOptions.year = 'numeric'; } else if (settings === axisTimeCombinations.HOUR_DAY || settings === axisTimeCombinations.MINUTE_HOUR) { format = monthDayHourFormat; localeOptions.hour = 'numeric'; } else if (settings === axisTimeCombinations.CUSTOM && typeof dateCustomFormat === 'string') { format = d3TimeFormat.timeFormat(dateCustomFormat); } if (locale && ((typeof Intl !== 'undefined') && (typeof Intl === 'object' && Intl.DateTimeFormat))) { let f = Intl.DateTimeFormat(locale, localeOptions); return f.format(date); } return format(date); }
javascript
{ "resource": "" }
q23471
_sortByTopicsOrder
train
function _sortByTopicsOrder(topics, order=topicsOrder) { return order.map((orderName) => topics.filter(({name}) => name === orderName)[0]); }
javascript
{ "resource": "" }
q23472
_sortByAlpha
train
function _sortByAlpha(topics) { return topics .map(d => d) .sort((a, b) => { if (a.name > b.name) return 1; if (a.name === b.name) return 0; return -1; }); let otherIndex = topics.map(({ name }) => name).indexOf('Other'); if (otherIndex >= 0) { let other = topics.splice(otherIndex, 1); topics = topics.concat(other); } }
javascript
{ "resource": "" }
q23473
updateContent
train
function updateContent(dataPoint){ var topics = dataPoint[topicLabel]; // sort order by topicsOrder array if passed if (topicsOrder.length) { topics = _sortByTopicsOrder(topics); } else if (topics.length && topics[0].name) { topics = _sortByAlpha(topics); } cleanContent(); updateTitle(dataPoint); resetSizeAndPositionPointers(); topics.forEach(updateTopicContent); }
javascript
{ "resource": "" }
q23474
updateTooltip
train
function updateTooltip(dataPoint, xPosition, yPosition) { updateContent(dataPoint); updatePositionAndSize(dataPoint, xPosition, yPosition); }
javascript
{ "resource": "" }
q23475
train
function(text, fontSize = defaultTextSize, fontFace = defaultFontFace) { let a = document.createElement('canvas'), b = a.getContext('2d'); b.font = fontSize + 'px ' + fontFace; return b.measureText(text).width; }
javascript
{ "resource": "" }
q23476
buildScales
train
function buildScales() { colorScale = d3Scale.scaleLinear() .range([colorSchema[0], colorSchema[colorSchema.length - 1]]) .domain(d3Array.extent(data, getValue)) .interpolate(d3Interpolate.interpolateHcl); }
javascript
{ "resource": "" }
q23477
drawBoxes
train
function drawBoxes() { boxes = svg.select('.chart-group').selectAll('.box').data(data); boxes.enter() .append('rect') .classed('box', true) .attr('width', boxSize) .attr('height', boxSize) .attr('x', ({hour}) => hour * boxSize) .attr('y', ({day}) => day * boxSize) .style('opacity', boxInitialOpacity) .style('fill', boxInitialColor) .style('stroke', boxBorderColor) .style('stroke-width', boxBorderSize) .transition() .duration(animationDuration) .style('fill', ({value}) => colorScale(value)) .style('opacity', boxFinalOpacity); boxes.exit().remove(); }
javascript
{ "resource": "" }
q23478
drawDayLabels
train
function drawDayLabels() { let dayLabelsGroup = svg.select('.day-labels-group'); dayLabels = svg.select('.day-labels-group').selectAll('.day-label') .data(daysHuman); dayLabels.enter() .append('text') .text((label) => label) .attr('x', 0) .attr('y', (d, i) => i * boxSize) .style('text-anchor', 'start') .style('dominant-baseline', 'central') .attr('class', 'day-label'); dayLabelsGroup.attr('transform', `translate(-${dayLabelWidth}, ${boxSize / 2})`); }
javascript
{ "resource": "" }
q23479
drawHourLabels
train
function drawHourLabels() { let hourLabelsGroup = svg.select('.hour-labels-group'); hourLabels = svg.select('.hour-labels-group').selectAll('.hour-label') .data(hoursHuman); hourLabels.enter() .append('text') .text((label) => label) .attr('y', 0) .attr('x', (d, i) => i * boxSize) .style('text-anchor', 'middle') .style('dominant-baseline', 'central') .attr('class', 'hour-label'); hourLabelsGroup.attr('transform', `translate(${boxSize / 2}, -${hourLabelHeight})`); }
javascript
{ "resource": "" }
q23480
addGlowFilter
train
function addGlowFilter(el) { if (!highlightFilter) { highlightFilter = createFilterContainer(svg.select('.metadata-group')); highlightFilterId = createGlowWithMatrix(highlightFilter); } let glowEl = d3Selection.select(el); glowEl .style('stroke-width', highlightCircleActiveStrokeWidth) .style('stroke-opacity', highlightCircleActiveStrokeOpacity) .attr('filter', `url(#${highlightFilterId})`); bounceCircleHighlight( glowEl, ease, highlightCircleActiveRadius ); }
javascript
{ "resource": "" }
q23481
buildLayers
train
function buildLayers() { dataByDateFormatted = dataByDate .map(d => assign({}, d, d.values)) .map(d => { Object.keys(d).forEach(k => { const entry = d[k]; if (entry && entry.name) { d[entry.name] = entry.value; } }); return assign({}, d, { date: new Date(d['key']) }); }); dataByDateZeroed = dataByDate .map(d => assign({}, d, d.values)) .map(d => { Object.keys(d).forEach(k => { const entry = d[k]; if (entry && entry.name) { d[entry.name] = 0; } }); return assign({}, d, { date: new Date(d['key']) }); }); let initialTotalsObject = uniq(data.map(getName)) .reduce((memo, key) => ( assign({}, memo, {[key]: 0}) ), {}); let totals = data .reduce((memo, item) => ( assign({}, memo, {[item.name]: memo[item.name] += item.value}) ), initialTotalsObject); order = topicsOrder || formatOrder(totals); let stack3 = d3Shape.stack() .keys(order) .order(d3Shape.stackOrderNone) .offset(d3Shape.stackOffsetNone); layersInitial = stack3(dataByDateZeroed); layers = stack3(dataByDateFormatted); }
javascript
{ "resource": "" }
q23482
formatOrder
train
function formatOrder(totals) { let order = Object.keys(totals) .sort((a, b) => { if (totals[a] > totals[b]) return -1; if (totals[a] === totals[b]) return 0; return 1; }); let otherIndex = order.indexOf('Other'); if (otherIndex >= 0) { let other = order.splice(otherIndex, 1); order = order.concat(other); } return order; }
javascript
{ "resource": "" }
q23483
createFakeData
train
function createFakeData() { const numDays = diffDays(emptyDataConfig.minDate, emptyDataConfig.maxDate) const emptyArray = Array.apply(null, Array(numDays)); isUsingFakeData = true; return [ ...emptyArray.map((el, i) => ({ [dateLabel]: addDays(emptyDataConfig.minDate, i), [valueLabel]: 0, [keyLabel]: '1', })), ...emptyArray.map((el, i) => ({ [dateLabel]: addDays(emptyDataConfig.minDate, i), [valueLabel]: 0, [keyLabel]: '2', })) ]; }
javascript
{ "resource": "" }
q23484
cleanData
train
function cleanData(originalData) { originalData = originalData.length === 0 ? createFakeData() : originalData; return originalData.reduce((acc, d) => { d.date = new Date(d[dateLabel]), d.value = +d[valueLabel] return [...acc, d]; }, []); }
javascript
{ "resource": "" }
q23485
drawEmptyDataLine
train
function drawEmptyDataLine() { let emptyDataLine = d3Shape.line() .x( (d) => xScale(d.date) ) .y( () => yScale(0) - 1 ); let chartGroup = svg.select('.chart-group'); chartGroup .append('path') .attr('class', 'empty-data-line') .attr('d', emptyDataLine(dataByDateFormatted)) .style('stroke', 'url(#empty-data-line-gradient)'); chartGroup .append('linearGradient') .attr('id', 'empty-data-line-gradient') .attr('gradientUnits', 'userSpaceOnUse') .attr('x1', 0) .attr('x2', xScale(data[data.length - 1].date)) .attr('y1', 0) .attr('y2', 0) .selectAll('stop') .data([ {offset: '0%', color: lineGradient[0]}, {offset: '100%', color: lineGradient[1]} ]) .enter() .append('stop') .attr('offset', ({offset}) => offset) .attr('stop-color', ({color}) => color); }
javascript
{ "resource": "" }
q23486
drawVerticalMarker
train
function drawVerticalMarker() { // Not ideal, we need to figure out how to call exit for nested elements if (verticalMarkerContainer) { svg.selectAll('.vertical-marker-container').remove(); } verticalMarkerContainer = svg.select('.metadata-group') .append('g') .attr('class', 'vertical-marker-container') .attr('transform', 'translate(9999, 0)'); verticalMarkerLine = verticalMarkerContainer.selectAll('path') .data([{ x1: 0, y1: 0, x2: 0, y2: 0 }]) .enter() .append('line') .classed('vertical-marker', true) .attr('x1', 0) .attr('y1', chartHeight) .attr('x2', 0) .attr('y2', 0); }
javascript
{ "resource": "" }
q23487
getDataByDate
train
function getDataByDate(data) { return d3Collection.nest() .key(getDate) .entries( data.sort((a, b) => a.date - b.date) ) .map(d => { return assign({}, d, { date: new Date(d.key) }); }); // let b = d3Collection.nest() // .key(getDate).sortKeys(d3Array.ascending) // .entries(data); }
javascript
{ "resource": "" }
q23488
getMaxValueByDate
train
function getMaxValueByDate() { let keys = uniq(data.map(o => o.name)); let maxValueByDate = d3Array.max(dataByDateFormatted, function(d){ let vals = keys.map((key) => d[key]); return d3Array.sum(vals); }); return maxValueByDate; }
javascript
{ "resource": "" }
q23489
setEpsilon
train
function setEpsilon() { let dates = dataByDate.map(({date}) => date); epsilon = (xScale(dates[1]) - xScale(dates[0])) / 2; }
javascript
{ "resource": "" }
q23490
handleMouseOver
train
function handleMouseOver(e, d) { overlay.style('display', 'block'); verticalMarkerLine.classed('bc-is-active', true); dispatcher.call('customMouseOver', e, d, d3Selection.mouse(e)); }
javascript
{ "resource": "" }
q23491
handleTouchMove
train
function handleTouchMove(e, d) { dispatcher.call('customTouchMove', e, d, d3Selection.touch(e)); }
javascript
{ "resource": "" }
q23492
handleHighlightClick
train
function handleHighlightClick(e, d) { dispatcher.call('customDataEntryClick', e, d, d3Selection.mouse(e)); }
javascript
{ "resource": "" }
q23493
adjustLines
train
function adjustLines() { let lineWidth = svg.select('.legend-line').node().getBoundingClientRect().width + markerSize; let lineWidthSpace = chartWidth - lineWidth; if (lineWidthSpace <= 0) { splitInLines(); } centerInlineLegendOnSVG(); }
javascript
{ "resource": "" }
q23494
buildContainerGroups
train
function buildContainerGroups() { let container = svg .append('g') .classed('legend-container-group', true) .attr('transform', `translate(${margin.left},${margin.top})`); container .append('g') .classed('legend-group', true); }
javascript
{ "resource": "" }
q23495
centerInlineLegendOnSVG
train
function centerInlineLegendOnSVG() { let legendGroupSize = svg.select('g.legend-container-group').node().getBoundingClientRect().width + getLineElementMargin(); let emptySpace = width - legendGroupSize; let newXPosition = (emptySpace/2); if (emptySpace > 0) { svg.select('g.legend-container-group') .attr('transform', `translate(${newXPosition},0)`) } }
javascript
{ "resource": "" }
q23496
centerVerticalLegendOnSVG
train
function centerVerticalLegendOnSVG() { let legendGroupSize = svg.select('g.legend-container-group').node().getBoundingClientRect().width; let emptySpace = width - legendGroupSize; let newXPosition = (emptySpace / 2) - (legendGroupSize / 2); if (emptySpace > 0) { svg.select('g.legend-container-group') .attr('transform', `translate(${newXPosition},0)`) } }
javascript
{ "resource": "" }
q23497
cleanData
train
function cleanData(data) { hasQuantities = data.filter(hasQuantity).length === data.length; return data .reduce((acc, d) => { if (d.quantity !== undefined && d.quantity !== null) { d.quantity = +d.quantity; } d.name = String(d.name); d.id = +d.id; return [...acc, d]; }, []); }
javascript
{ "resource": "" }
q23498
drawHorizontalLegend
train
function drawHorizontalLegend() { let xOffset = markerSize; svg.select('.legend-group') .selectAll('g') .remove(); // We want a single line svg.select('.legend-group') .append('g') .classed('legend-line', true); // And one entry per data item entries = svg.select('.legend-line') .selectAll('g.legend-entry') .data(data); // Enter entries.enter() .append('g') .classed('legend-entry', true) .attr('data-item', getId) .attr('transform', function({name}) { let horizontalOffset = xOffset, lineHeight = chartHeight / 2, verticalOffset = lineHeight, labelWidth = textHelper.getTextWidth(name, textSize); xOffset += markerSize + 2 * getLineElementMargin() + labelWidth; return `translate(${horizontalOffset},${verticalOffset})`; }) .merge(entries) .append('circle') .classed('legend-circle', true) .attr('cx', markerSize/2) .attr('cy', markerYOffset) .attr('r', markerSize / 2) .style('fill', getCircleFill) .style('stroke-width', 1); svg.select('.legend-group') .selectAll('g.legend-entry') .append('text') .classed('legend-entry-name', true) .text(getName) .attr('x', getLineElementMargin()) .style('font-size', `${textSize}px`) .style('letter-spacing', `${textLetterSpacing}px`); // Exit svg.select('.legend-group') .selectAll('g.legend-entry') .exit() .transition() .style('opacity', 0) .remove(); adjustLines(); }
javascript
{ "resource": "" }
q23499
drawVerticalLegend
train
function drawVerticalLegend() { svg.select('.legend-group') .selectAll('g') .remove(); entries = svg.select('.legend-group') .selectAll('g.legend-line') .data(data); // Enter entries.enter() .append('g') .classed('legend-line', true) .append('g') .classed('legend-entry', true) .attr('data-item', getId) .attr('transform', function(d, i) { let horizontalOffset = markerSize + getLineElementMargin(), lineHeight = chartHeight/ (data.length + 1), verticalOffset = (i + 1) * lineHeight; return `translate(${horizontalOffset},${verticalOffset})`; }) .merge(entries) .append('circle') .classed('legend-circle', true) .attr('cx', markerSize/2) .attr('cy', markerYOffset) .attr('r', markerSize/2 ) .style('fill', getCircleFill) .style('stroke-width', 1); svg.select('.legend-group') .selectAll('g.legend-line') .selectAll('g.legend-entry') .append('text') .classed('legend-entry-name', true) .text(getName) .attr('x', getLineElementMargin()) .style('font-size', `${textSize}px`) .style('letter-spacing', `${textLetterSpacing}px`); if (hasQuantities) { writeEntryValues(); } else { centerVerticalLegendOnSVG(); } // Exit svg.select('.legend-group') .selectAll('g.legend-line') .exit() .transition() .style('opacity', 0) .remove(); }
javascript
{ "resource": "" }