Create a combined bar/line chart with dimplejs and use self-defined colors - dimple.js

I'm trying to create a combined bar/line chart based on a simple data set (columns: countries, index1, index2, index3, ...) using dimplejs. Index1 will be the bar chart and index2 upwards should be dynamically (=adding and removing indices per user interaction) displayed as line charts on top.
I found out that I seemingly needed to create a hidden 2nd x-axis for the line graphics. Is there any other way?
I was also unable to add more than one index as line chart. Is there a way to add more lines where each one is based on a column (index2, index3, ...)?
Defining colors was another problem: The bars are all in one color which is good but if I want to assign a color myself I have to give the data a tag which is displayed in the tooltip (not good)?
Assigning colors to the line charts didn't work at all for me. I would need some advice here.
My code so far:
var svg = dimple.newSvg("#graphic", 550, 700);
// Get data for one year
var filteredData = dimple.filterData(data, 'year', '2010');
var myChart = new dimple.chart(svg, filteredData);
myChart.setBounds(50, 30, 480, 630);
var xAxis = myChart.addMeasureAxis('x', 'index1');
xAxis.title = 'Index Value';
xAxis.overrideMax = 1;
var yAxis = myChart.addCategoryAxis('y', 'countries');
yAxis.title = 'Country';
var xAxis2 = myChart.addMeasureAxis('x', 'index2');
xAxis2.title = null;
xAxis2.overrideMax = 1;
xAxis2.hidden = true;
var bars = myChart.addSeries('bars', dimple.plot.bar, [xAxis,yAxis]);
myChart.assignColor('bars', '#D3D3D3', '#D3D3D3');
var lines = myChart.addSeries('index2', dimple.plot.line, [xAxis2,yAxis]);
yAxis.addOrderRule('index1', false);
myChart.draw();

That data structure is not ideal for your data requirement within dimple. The way dimple would like that data is with your index names as dimension values:
var data = [
{ "Index" : "Index 1", "Country" : "UK", "Index Value": 0.2 },
{ "Index" : "Index 1", "Country" : "Spain", "Index Value": 0.7 },
{ "Index" : "Index 2", "Country" : "UK", "Index Value": 0.5 },
{ "Index" : "Index 2", "Country" : "Spain", "Index Value": 0.6 },
{ "Index" : "Index 3", "Country" : "UK", "Index Value": 0.4 },
{ "Index" : "Index 3", "Country" : "Spain", "Index Value": 0.3 },
...
];
Then in order to draw index 1 as a bar and the rest as lines you would need to split your data set into 2:
var barData = [],
lineData = [],
i,
keyIndex = "Index 1";
for (i = 0; i < data.length; i += 1) {
if (data[i]["Index"] === keyIndex) {
barData.push(data[i]);
} else {
lineData.push(data[i]);
}
}
You could then just define your chart as follows:
var chart = new dimple.chart(svg),
bars,
lines;
chart.addMeasureAxis("x", "Index Value");
chart.addCategoryAxis("y", "Country");
bars = chart.addSeries("Index", dimple.plot.bar);
bars.data = barData;
lines = chart.addSeries("Index", dimple.plot.line);
lines.data = lineData;
chart.draw();
I haven't tested this code but it ought to do what you want (minus the formatting etc).
If you want to continue on the road you have started in your code above (which is still possible) you will find composite axes very helpful to avoid hidden secondary axes and potential problems with differing max/min values. See the relevant section in the version 2 release notes for an example of these.
I don't understand why you don't want to tag the indices with something which appears in the tooltip, there must be some difference between them which you can communicate, but if you want to remove the index name from the tooltip you can define custom tooltips as shown here.
Edit: I should add if you just want to change the set of colours which dimple will arbitrarily ascribe to your data points you can override the default colours in the chart object as discussed here.

Related

Schema Length Validation Error on Python Dash DataTable

I am building a dashboard using python dash and have a requirement of datatable with multiple dropdowns. The dataframe is created one with groupby (multiple columns) and aggregation.
I have written the code as below:
'''
app = JupyterDash()
app.layout = html.Div(children = [html.H2('SPEND PLANNING',
style = {'background-color':'#C0C0C0',
'border': '5px solid',
'font-family':'Serif',
'font-size': 25,
'text-align':'center',
'margin':'auto',
'justify-content': 'space-evenly',
'width':'100%'
}),
html.H1(),
html.Div(children = [dcc.Dropdown(
id ='period-filter',
options = dict([{"label": i, "value": i} for i in s2['PERIOD'].unique()]),
value = s2['PERIOD'].max(),
multi = True,
searchable=True,
style = {'display':'inline-block','width':'48%','vertical-align':'top'},
clearable=False,
placeholder="Quarter"
)]),
html.H1(),
html.Div(children = [dcc.Dropdown(
id ='commodity-filter',
options = dict([{"label": i, "value": i} for i in s2['COMMODITY GROUP'].unique()]),
value = s2['COMMODITY GROUP'].max(),
multi = True,
searchable=True,
style = {'display':'inline-block','width':'48%'},
clearable=False,
placeholder= "Commodity Group"
)]),
html.H1(),
html.Div(children = [dt(
id = "datatable",
columns = [{"name": i, "id": i} for i in s2.columns],
editable = True,
data = s2.to_dict('records'),
multi = True
])
#app.callback(output = [Output("datatable", "data")],
inputs = [Input("period-filter", "value"),Input("commodity-filter","value")])
def display_table(comm,period):
filtered_df = s2.loc[(s2['COMMODITY GROUP'].eq('comm')) & (s2['PERIOD'].eq('period'))]
return filtered_df.to_dict('records')
if _name_ == "_main_":
app.run_server(debug=True)
'''
The error after running the script is below:
SchemaLengthValidationError: Schema: [<Output datatable.data>]
Path: ()
Expected length: 1
Received value of length 0:
[]
When I remove the [] from [Output("datatable", "data")] the error is gone, however the data in the table also disappears giving a blank table.
The dropdowns also do not show the values, instead shows only - value.
Please help me with the above.

RStudio shiny datatables save csv unquoted?

How can I save the output of an RStudio Shiny DataTables table using the Save to CSV extension, but have the content saved unquoted instead of the default, which is in double-quotes:
For example, for a single column with two entries, I get a file.csv like this:
"column_name"
"foo"
"bar"
And instead I would like either:
column_name
foo
bar
Or even better, without the header:
foo
bar
My current code looks like this:
output$mytable <- renderDataTable({
entries()
}, options = list(colnames = NULL, bPaginate = FALSE,
"sDom" = 'RMDT<"cvclear"C><"clear">lfrtip',
"oTableTools" = list(
"sSwfPath" = "copy_csv_xls.swf",
"aButtons" = list(
"copy",
"print",
list("sExtends" = "collection",
"sButtonText" = "Save",
"aButtons" = list("csv","xls")
)
)
)
)
)
EDIT:
I tried with one of the suggested answers, and ajax is not allowed, the page complains when I click on SaveTXT. If I do the following, it still puts things within double quotes:
list("sExtends" = "collection",
"sButtonText" = "SaveTXT",
"sFieldBoundary" = '',
"aButtons" = list("csv")
Any ideas?
It should be possible through button options:Button options
And changing sFieldBoundary value.
$(document).ready( function () {
$('#example').dataTable( {
"sDom": 'T<"clear">lfrtip',
"oTableTools": {
"aButtons": [
{
"sExtends": "ajax",
"sFieldBoundary": '"'
}
]
}
} );
} );
But I couldn't get it working in shiny.

Dojo charting: Can i change the color of the line based on the value?

I have a working chart with Dojo 1.8.
chart1 = new dojox.charting.Chart2D("chart1");
chart1.addPlot("default", {type: "Lines", ...
chart1.addSeries("Series A", [{ x: 1, y: 2.3, tooltip: "Value 1"}, ...
My data from the series gets displayed correctly as line and the whole line (series) gets the color 'Green'.
I know how to change the color for the whole series, but would it be possible that the line changes its color based on the data values? Lets assume the x-axis is a time axis and I need the line (series) to be green for until today, and then red for the future values.
Would this be possible and how ?
(I am using markers for the values. If these could change based on the value it would be enough)
I found something something like this in the documentation:
chart.addSeries("Series A", [
{y: 4, color: "red"},
{y: 2, color: "green"},
{y: 1, color: "blue"},
{y: 1, text: "Other", **color: "white", fontColor: "red"**}
]);
But it only works for PIE-charts and not for LINES-charts.
Thank you in advance.
You could try this http://jsfiddle.net/jUS54/
Use styleFunc in the addPlot method for change the markers colors:
var chart1 = new Chart("simplechart");
chart1.addPlot("default", {type: Lines, markers:true, styleFunc: function(item {
if(item <= 2){
return { fill : "red" };
}else if(item > 3){
return { fill: "green" };
}
return {};
}});
You can change the color by adding 'fill' to your chart data. Basically, loop through your input data deciding what to set your fill too while constructing the JSON for chartData.
var chartData = [{y: 10000,fill: "red"},{y:9200,fill: "yellow"},{y:11811,fill: "green"},{y:12000,fill: "blue"},{y:7662,fill: "blue"},{y:13887,fill: "black"},{y:14200,fill: "gray"},{y:12222,fill: "purple"},{y:12000,fill: "green"},{y:10009,fill: "purple"},{y:11288,fill: "green"},{y:12099,fill: "blue"}];
http://jsfiddle.net/goinoff/QnNk2/1/

facets with ravendb

i am trying to work with the facet ability in ravendb but getting strange results.
i have a documents like :
{
"SearchableModel": "42LC2RR ",
"ModelName": "42LC2RR",
"ModelID": 490578,
"Name": "LG 42 Television 42LC2RR",
"Desctription": "fffff",
"Image": "1/4/9/8/18278941c",
"MinPrice": 9400.0,
"MaxPrice": 9400.0,
"StoreAmounts": 1,
"AuctionAmounts": 0,
"Popolarity": 3,
"ViewScore": 0.0,
"ReviewAmount": 2,
"ReviewScore": 45,
"Sog": "E-TV",
"SogID": 1,
"IsModel": true,
"Manufacrurer": "LG",
"ParamsList": [
"1994267",
"46570",
"4134",
"4132",
"4118",
"46566",
"4110",
"180676",
"239517",
"750771",
"2658507",
"2658498",
"46627",
"4136",
"169941",
"169846",
"145620",
"169940",
"141416",
"3190767",
"3190768",
"144720",
"2300706",
"4093",
"4009",
"1418470",
"179766",
"190025",
"170557",
"170189",
"43768",
"4138",
"67976",
"239516",
"3190771",
"141195"
],
}
where the ParamList each represents a property of the product and in our application we have in cache what each param represents.
when searching for a specific product i would like to count all the returning attributes to be able to add the amount of each item after the search.
After searching lg in televisions category i want to get :
Param:4134 witch is a representative of LCD and the amount :65.
but unfortunately i am getting strange results. only some params are counted and some not.
on some searchers where i am getting results back i dont get any amounts back.
i am using the latest stable version of RavenDB.
index :
from doc in docs
from param in doc.ParamsList
select new {Name=doc.Name,Description=doc.Description,SearchNotVisible = doc.SearchNotVisible,SogID=doc.SogID,Param =param}
facet :
DocumentStore documentStore = new DocumentStore { ConnectionStringName = "Server" };
documentStore.Initialize();
using (IDocumentSession session = documentStore.OpenSession())
{
List<Facet> _facets = new List<Facet>
{
new Facet {Name = "Param"}
};
session.Store(new FacetSetup { Id = "facets/Params", Facets = _facets });
session.SaveChanges();
}
usage example :
IDictionary<string, IEnumerable<FacetValue>> facets = session.Advanced.DatabaseCommands.GetFacets("FullIndexParams", new IndexQuery { Query = "Name:lg" }, "facets/Params");
i tried many variations without success.
does anyone have ideas what am i doing wrong ?
Thanks
Use this index, it should resolve your problem:
from doc in docs
select new {Name=doc.Name,Description=doc.Description,SearchNotVisible = doc.SearchNotVisible,SogID=doc.SogID,Param = doc.ParamsList}
What analyzer you set for "Name" field. I see you search by Name "lg". By default, Ravendb use KeywordAnalyzer, means you must search by exact name. You should set another analyzer for Name or Description field (StandardAnalyzer for example).

RavenDB facet takes to long query time

I am new to ravendb and trying it out to see if it can do the job for the company i work for .
i updated a data of 10K records to the server .
each data looks like this :
{
"ModelID": 371300,
"Name": "6310I",
"Image": "0/7/4/9/28599470c",
"MinPrice": 200.0,
"MaxPrice": 400.0,
"StoreAmounts": 4,
"AuctionAmounts": 0,
"Popolarity": 16,
"ViewScore": 0.0,
"ReviewAmount": 4,
"ReviewScore": 40,
"Cat": "E-Cellphone",
"CatID": 1100,
"IsModel": true,
"ParamsList": [
{
"ModelID": 371300,
"Pid": 188396,
"IntVal": 188402,
"Param": "Nokia",
"Name": "Manufacturer",
"Unit": "",
"UnitDir": "left",
"PrOrder": 0,
"IsModelPage": true
},
{
"ModelID": 371305,
"Pid": 398331,
"IntVal": 1559552,
"Param": "1.6",
"Name": "Screen size",
"Unit": "inch",
"UnitDir": "left",
"PrOrder": 1,
"IsModelPage": false
},.....
where ParamsList is an array of all the attributes of a single product.
after building an index of :
from doc in docs.FastModels
from docParamsListItem in ((IEnumerable<dynamic>)doc.ParamsList).DefaultIfEmpty()
select new { Param = docParamsListItem.IntVal, Cat = doc.Cat }
and a facet of
var facetSetupDoc = new FacetSetup
{
Id = "facets/Params2Facets",
Facets = new List<Facet> { new Facet { Name = "Param" } }
};
and search like this
var facetResults = session.Query<FastModel>("ParamNewIndex")
.Where(x => x.Cat == "e-cellphone")
.ToFacets("facets/Params2Facets");
it takes more than a second to query and that is on only 10K of data . where our company has more than 1M products in DB.
am i doing something wrong ?
In order to generate facets, you have to check for each & every individual value of docParamsListItem.IntVal. If you have a lot of them, that can take some time.
In general, you shouldn't have a lot of facets, since that make no sense, it doesn't help the user.
For integers, you usually use ranges, instead of the actual values.
For example, price within a certain range.
You use just the field for things like manufacturer, or the MegaPixels count, where you have lot number or items (about a dozen or two)
You didn't mention which build you are using, but we made some major improvements there recently.