cal-heatmap - legendColors as array of color values? - d3.js

I am trying out cal-heatmap, and I want to supply a simple array of the legend colors to use, rather than having to define CSS classes for each color.
So far in my testing this doesn't seem possible?
for example, using:
legendColors : ['rgb(103,0,31)','rgb(178,24,43)','rgb(214,96,77)','rgb(244,165,130)','rgb(253,219,199)','rgb(224,224,224)','rgb(186,186,186)','rgb(135,135,135)','rgb(77,77,77)','rgb(26,26,26)'],
Gives me a scale with 10 steps from the first to the second color, ignoring the rest.
Am I missing something simple in the documentation, or is this not possible?
I know that I can create CSS classes, but I don't want to do that - I need to have a dynamic, variable number of categories, with dynamically created colors.

I looked through the API and source code and it doesn't seem possible. Two thoughts come to mind:
One, fix it after the fact:
cal.init({
range: 10,
start: new Date(2000, 0, 1, 1),
data: "datas-hours.json",
onComplete: function() {
setTimeout(function(){
['rgb(103,0,31)','rgb(178,24,43)','rgb(214,96,77)','rgb(244,165,130)','rgb(253,219,199)','rgb(224,224,224)','rgb(186,186,186)','rgb(135,135,135)','rgb(77,77,77)','rgb(26,26,26)']
.forEach(function(d,i){
d3.selectAll("rect.r" + i)
.style("fill", d);
});
}, 10);
}
I'm not sure why the setTimeout is necessary and this produces an odd "flash" affect as the colors are swapped. Example here.
Another idea is to write the styles on the fly:
var style = document.createElement('style');
style.type = 'text/css';
['rgb(103,0,31)','rgb(178,24,43)','rgb(214,96,77)','rgb(244,165,130)','rgb(253,219,199)','rgb(224,224,224)','rgb(186,186,186)','rgb(135,135,135)','rgb(77,77,77)','rgb(26,26,26)']
.forEach(function(d,i){
style.innerHTML += ".q" + i + " {fill:" + d + "; background-color: " + d + "}";
});
document.getElementsByTagName('head')[0].appendChild(style);
var cal = new CalHeatMap();
cal.init({
range: 10,
start: new Date(2000, 0, 1, 1),
data: "datas-hours.json"
});
Example here.
Not sure I like either of these options, though. You'd probably be better forking the repository, adding what you want and submitting a pull request. Look down at line 3278 and swap out that color scale with your ordinal one.

Related

Showing the percentage value in pie chart

console.log(group1.top(Infinity));
gives me:
0:
key: "M"
value: {Recovered: 122, Hospitalized: 38922, Deceased: 641, Migrated_Other: 1}
__proto__: Object
1:
key: "F"
value: {Recovered: 82, Hospitalized: 19215, Deceased:.....
In this code:
.label(function(d) {
return d.key+": " + (d.value[type]/<?> * 100).toFixed(2) + "%";
})
if the type is Recovered then I want the sum of recovered values (122+82) in place of <?> i.e d.value["Recovered"]/(122+82)
I am just stuck at the syntax how to take the sum of values of the matched type in place of <?>.
I can only think of
group1.all()[0].value['Recovered']+group1.all()[1].value['Recovered']
Is there any better way?
Working Code:
https://blockbuilder.org/ninjakx/61d405cb0aaeda3be960e836f803cdd5
There are a couple of ways to do this. One is to compute the sum, manually as you show above, or by using a groupAll object.
The other way, which the pie chart example uses, is to use the angle data saved in the pie slices:
// workaround for #703: not enough data is accessible through .label() to display percentages
.on('pretransition', function(chart) {
chart.selectAll('text.pie-slice').text(function(d) {
return d.data.key + ' ' + dc.utils.printSingleValue((d.endAngle - d.startAngle) / (2*Math.PI) * 100) + '%';
})
});
As noted, there is not enough data supplied to .label() to use this approach, so this is applied after drawing, using the full data objects.

Unable to filter individual stacks using dc.js with multiple X keys

Stacked Bar chart not able to filter on click of any Stack
I need to filter all the charts when clicking on any stack, which is not happening and struggling for a few days.
I've created a fiddle with link
http://jsfiddle.net/praveenNbd/09t5fd7v/13/
I feel am messing up with keys creation as suggested by gordonwoodhull.
function stack_second(group) {
return {
all: function () {
var all = group.all(),
m = {};
// build matrix from multikey/value pairs
all.forEach(function (kv) {
var ks = kv.key;
m[ks] = kv.value;
});
// then produce multivalue key/value pairs
return Object.keys(m).map(function (k) {
return {
key: k,
value: m[k]
};
});
}
};
}
I tried to follow this example https://dc-js.github.io/dc.js/examples/filter-stacks.html
Not able to figure out how below code works:
barChart.on('pretransition', function (chart) {
chart.selectAll('rect.bar')
.classed('stack-deselected', function (d) {
// display stack faded if the chart has filters AND
// the current stack is not one of them
var key = multikey(d.x, d.layer);
//var key = [d.x, d.layer];
return chart.filter() && chart.filters().indexOf(key) === -1;
})
.on('click', function (d) {
chart.filter(multikey(d.x, d.layer));
dc.redrawAll();
});
});
Can someone please point me out in the right direction.
Thanks for stopping by.
You usually don't want to use multiple keys for the X axis unless you have a really, really good reason. It is just going to make things difficult
Here, the filter-stacks example is already using multiple keys, and your data also has multiple keys. If you want to use your data with this example, I would suggest crunching together the two keys, since it looks like you are really using the two together as an ordinal key. We'll see one way to do that below.
You were also trying to combine two different techniques for stacking the bars, stack_second() and your own custom reducer. I don't think your custom reducer will be compatible with filtering by stacks, so I will drop it in this answer.
You'll have to use the multikey() function, and crunch together your two X keys:
dim = ndx.dimension(function (d) {
return multikey(d[0] + ',' + d[1], d[2]);
});
Messy, as this will create keys that look like 0,0xRejected... not so human-readable, but the filter-stacks hack relies on being able to split the key into two parts and this will let it do that.
I didn't see any good reason to use a custom reduction for the row chart, so I just used reduceCount:
var barGrp = barDim.group();
I found a couple of new problems when working on this.
First, your data doesn't have every stack for every X value. So I added a parameter to stack_second() include all the "needed" stacks:
function stack_second(group, needed) {
return {
all: function() {
var all = group.all(),
m = {};
// build matrix from multikey/value pairs
all.forEach(function(kv) {
var ks = splitkey(kv.key);
m[ks[0]] = m[ks[0]] || Object.fromEntries(needed.map(n => [n,0]));
m[ks[0]][ks[1]] = kv.value;
});
// then produce multivalue key/value pairs
return Object.entries(m).map(([key,value]) => ({key,value}));
}
};
}
Probably the example should incorporate this change, although the data it uses doesn't need it.
Second, I found that the ordinal X scale was interfering, because there is no way to disable the selection greying behavior for bar charts with ordinal scales. (Maybe .brushOn(false) is completely ignored? I'm not sure.)
I fixed it in the pretransition handler by explicitly removing the built-in deselected class, so that our custom click handler and stack-deselected class can do their work:
chart.selectAll('rect.bar')
.classed('deselected', false)
All in all, I think this is way too complicated and I would advise not to use multiple keys for the X axis. But, as always, there is a way to make it work.
Here is a working fork of your fiddle.

Simple way to add raw data to dc.js composite chart via Ajax

I have a composite chart of 2 line charts however I need to add a third chart to it.
This third chart will have these unique properties:
The data will come in via an ajax call and be available as a two dimensional array [[timestamp,value],[timestamp,value]...]
Every new ajax call needs to replace the values of the previous one
It does not need to respect any of the filters and will not be used on any other charts
It will however need to use a differently scaled Y axis.. (and labeled so on the right)
This is how the chart currently looks with only two of the charts
This is my code with the start of a third line graph... Assuming I have the array of new data available i'm at a little loss of the best/simplest way to handle this.
timeChart
.width(width).height(width*.333)
.dimension(dim)
.renderHorizontalGridLines(true)
.x(d3.time.scale().domain([minDate,maxDate]))
.xUnits(d3.time.months)
.elasticY(true)
.brushOn(true)
.legend(dc.legend().x(60).y(10).itemHeight(13).gap(5))
.yAxisLabel(displayName)
.compose([
dc.lineChart(timeChart)
.colors(['blue'])
.group(metric, "actual" + displayName)
.valueAccessor (d) -> d.value.avg
.interpolate('basis-open')
.dimension(dim),
dc.lineChart(timeChart)
.colors(['red'])
.group(metric, "Normal " + displayName)
.valueAccessor (d) -> d.value.avg_avg
.interpolate('basis-open'),
dc.lineChart(timeChart)
.colors(['#666'])
.y()#This needs to be scaled and labeled on the right side of the chart
.group() #I just want to feed a simple array of values into here
])
Also side note: I've noticed what I might be a small bug with the legend rendering. As you can see in the legend both have the same label but i've used different strings in the second .group() argument.
I believe you are asking a few questions here. I will try to answer the main question: how do you add data to a dc chart.
I created an example here: http://jsfiddle.net/djmartin_umich/qBr7y/
In this example I simply add random data to the crossfilter, though this could easily be adapted to pull data from the server:
function AddData(){
var q = Math.floor(Math.random() * 6) + 1;
currDate = currDate.add('month', 1);
cf.add( [{date: currDate.clone().toDate(), quantity: q}]);
$("#log").append(q + ", ");
}
I call this method once a second. Once it completes, I reset the x domain and redraw the chart.
window.setInterval(function(){
AddData();
lineChart.x(d3.time.scale().domain([startDate, currDate]));
dc.redrawAll();
}, 1000);
I recommend trying to get this working in isolation before trying to add the complexity of multiple y-axis scales.
Currently your best bet is to create a fake group. Really the .data method on the charts is supposed to do this, but it doesn't work for charts that derive from the stack mixin.
https://github.com/dc-js/dc.js/wiki/FAQ#filter-the-data-before-its-charted

Trouble with filters and triggers in dc.js - re-drawing is out of sync

I have two plots: a line plot and a bubble plot. When I click on the bubble plot, I want the line plot to be updated so that it is drawn with only the data related to that 'bubble'. This is different from the standard implementation whereby clicking would add or remove the data from the existing filter.
If you look at the image you can see that although 'model 0' is selected the plotted hazard (y-scale in plot 1) does not correspond.
And now when I click on 'model 5', I get the opposite.
My current implementation is posted as a jsfiddle here. I can see from the attached data table that I am achieving what I want, but the line plot does not re-draw correctly. In fact, it seems to re-draw with the last filter, not the new one.
This implementation is hacked from here: in particular, the renderlet and on("filtered", function (chart) { lines. However, to make this work, I have had to comment out the plot1.filter(chart.filter()); line for the second plot.
I don't really understand why a renderlet and the on("filtered" ... or on("postRedraw" ... listeners are needed together.
I have been round the houses on this one, so any suggestions would be very gratefully received.
I tried to simplify the jsfiddle to isolate the problem. Here is the adapted jsfiddle: http://jsfiddle.net/djmartin_umich/mKz7A/
Your plot2 keyAccessor accessed the df value from the p.value.df rather than using a dimension on df. My guess is that this is what was causing problems. Here is the adapted code:
dfDim = ndx.dimension(function (d) {return d.df;});
...
plot2.width(300)
.height(250)
.dimension(dfDim)
I also noticed that your plot2 valueAccessor and radiusAccessor were not using a computed average. Your code would overwrite est and estse for each record added or removed from the group. Here is the adapted code that computes the average:
dfGroup = dfDim.group().reduce(
//add
function (p, v) {
++p.count;
p.est += v.est;
p.avg_est = p.est / p.count;
p.estse += v.estse;
p.avg_estse = p.estse / p.count;
return p;
},
//remove
function (p, v) {
--p.count;
p.est -= v.est;
p.avg_est = p.est / p.count;
p.estse -= v.estse;
p.avg_estse = p.estse / p.count;
return p;
},
//init
function (p, v) {
return {
count: 0,
est: 0,
estse: 0,
avg_est: 0,
avg_estse: 0
};
});
After these changes, I believe the code behaves as you wanted.

Is an NVD3 Line Plot with Markers Possible?

I'm making an NVD3 line plot that will have significantly improved clarity if I can get markers to show for each data point instead of just the line itself. Unfortunately, I haven't been able to find an easy way to do this with NVD3 yet. I also considered using a scatter plot, but I couldn't figure out how to show connecting lines between the points. A third option I considered was to overlay a line and scatter plot, but this would show each series twice in the legend and may cause other unnecessary visual complications.
Is there a way to elegantly pull this off yet? Sample code of my formatting technique is listed below, but the 'size' and 'shape' attributes in test_data have no effect on the line plot with the current code.
test_data = [ { key: 'series1',
values: [
{ x: 1, y: 2.33, size:5, shape:"circle" },
{ x: 2, y: 2.34, size:5, shape:"circle" },
{ x: 3, y: 2.03, size:5, shape:"circle" },
] } ];
nv.addGraph(function() {
var test_chart = nv.models.lineChart();
test_chart.xAxis.axisLabel('Sample Number');
test_chart.yAxis
.axisLabel('Voltage (V)')
.tickFormat(d3.format('.02f'));
d3.select('#test_plot')
.datum(test_data)
.transition().duration(500)
.call(test_chart);
nv.utils.windowResize(test_chart.update);
return test_chart;
});
I also wanted to add markers in a project I was working on. Here is a solution my partner and I found.
First, you have to select all of the points in your chart and set the fill-opacity to 1:
#my-chart .nv-lineChart circle.nv-point
{
fill-opacity: 1;
}
Now your points will be visible. To adjust the size of each point you need to modify each one's "r" (for radius) attribute. This isn't a style so you can't do it with css. Here is some jQuery code that does the job. The 500 millisecond delay is so the code will not run before the chart is rendered. This snippet sets the radius to 3.5:
setTimeout(function() {
$('#my-chart .nv-lineChart circle.nv-point').attr("r", "3.5");
}, 500);
This puzzled me until I got help from the community:
css styling of points in figure
So here is my solution, based on css:
.nv-point {
stroke-opacity: 1!important;
stroke-width: 5px!important;
fill-opacity: 1!important;
}
If anyone has come here from rCharts, below is a rmarkdown template to create an nPlot with both lines and markers:
```{r 'Figure'}
require(rCharts)
load("data/df.Rda")
# round data for rChart tooltip display
df$value <- round(df$value, 2)
n <- nPlot(value ~ Year, group = 'variable', data = df, type = 'lineChart')
n$yAxis(axisLabel = 'Labor and capital income (% national income)')
n$chart(margin = list(left = 100)) # margin makes room for label
n$yAxis(tickFormat = "#! function(d) {return Math.round(d*100*100)/100 + '%'} !#")
n$xAxis(axisLabel = 'Year')
n$chart(useInteractiveGuideline=TRUE)
n$chart(color = colorPalette)
n$addParams(height = 500, width = 800)
n$setTemplate(afterScript = '<style>
.nv-point {
stroke-opacity: 1!important;
stroke-width: 6px!important;
fill-opacity: 1!important;
}
</style>'
)
n$save('figures/Figure.html', standalone = TRUE)
```
The current version of nvd3 use path instead of circle to draw markers. Here is a piece of css code that i used to show markers.
#chart g.nv-scatter g.nv-series-0 path.nv-point
{
fill-opacity: 1;
stroke-opacity: 1;
}
And I also write something about this in https://github.com/novus/nvd3/issues/321, you could find that how i change the shape of makers.
I don't know how to change the size of markers. Trying to find a solution.
Selectively enable points to some series using the following logic in nvd3.
//i is the series number; starts with 0
var selector = 'g.nv-series-'+i+' circle';
d3.selectAll(selector).classed("hover",true);
However an additional parameter( like say 'enable_points':'true') in the data would make better sense. I will hopefully push some changes to nvd3 with this idea.
For current version of NVD3 (1.8.x), I use this D3-based solution (scripting only, no CSS file or style block required):
nv.addGraph(function() {
// ...
return chart;
},
function() {
// this function is called after the chart is added to document
d3.selectAll('#myChart .nv-lineChart .nv-point').style("stroke-width",
"7px").style("fill-opacity", ".95").style("stroke-opacity", ".95");
}
);
The styles used are exactly the styles added by NVD3 by applying the "hover" class to each point (when hovered). Adjust them to your needs.

Resources