Skip to content

Instantly share code, notes, and snippets.

@jkeefe
Last active September 27, 2021 22:50
Show Gist options
  • Save jkeefe/00adc9bf5687d62225a2df5e5df90e2d to your computer and use it in GitHub Desktop.
Save jkeefe/00adc9bf5687d62225a2df5e5df90e2d to your computer and use it in GitHub Desktop.
Responsive Map Legend
/// legend css ///
.v-legend-hed {
font-weight: bold;
font-size: 16px;
margin-bottom: 12px;
width: 100%;
text-align: center;
margin-top: 20px;
}
.v-legend-colors-container {
display: flex;
justify-content: center;
margin-bottom: 2px;
}
.v-legend-colors {
margin-left: 1px;
margin-right: 1px;
}
.v-legend-labels-container {
display: flex;
justify-content: center;
margin-bottom: 20px;
}
.v-legend-labels {
margin-left: 1px;
margin-right: 1px;
text-align: center;
}
// // -- legend code -- // //
const legend_title = '7-day precipitation forecast, in inches';
const color_width = 70; // width in pixels
const breaks = [0.1, 0.5, 0.75, 1.25, 1.5, 2];
const colors = [
'#ffffcc',
'#c7e9b4',
'#7fcdbb',
'#41b6c4',
'#1d91c0',
'#225ea8',
'#0c2c84',
];
// assumes a previously-established container div
container
.append('div')
.attr('class', 'v-legend-hed')
.html(legend_title);
const map_legend = container
.append('div')
.attr('class', 'v-legend-colors-container')
.attr('width', initialWidth);
map_legend.selectAll('.v-legend-colors')
.data(colors)
.enter()
.append('div')
.attr('class', 'v-legend-colors')
.style('height', '8px')
.style('width', `${color_width}px`)
.style('background-color', d => d);
const map_legend_labels = container
.append('div')
.attr('class', 'v-legend-labels-container')
.attr('width', initialWidth);
map_legend_labels
.append('div')
.attr('class', 'v-legend-label-spacer')
.style('width', `${color_width / 2}px`);
map_legend_labels.selectAll('.v-legend-labels')
.data(breaks)
.enter()
.append('div')
.attr('class', 'v-legend-labels')
.style('width', `${color_width}px`)
.html(d => d);
map_legend_labels
.append('div')
.attr('class', 'v-legend-label-spacer')
.style('width', `${color_width / 2}px`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment