How do I set category values explicitly with dimple.js charts? - dimple.js

I want to draw a chart that always shows M, T, W, Th, F, Sa, Su on the x axis.
I start with:
var x = myChart.addCategoryAxis("x", "Day");
x.addOrderRule(["M", "T", "W", "Th", "F", "Sa", "Su"]);
but that won't force those values to exist; if my data only has "W" and "F", I'll only get two items on the x axis.
However, I want all 7 even if the data has no examples of some values.
Is there a way to achieve this?
I also posted this as an issue, but it's probably more appropriate here on SO:
https://github.com/PMSI-AlignAlytics/dimple/issues/103

You just need to make sure those values appear in your data. Here's an example:
var xValues = ["M", "T", "W", "Th", "F", "Sa", "Su"];
svg = dimple.newSvg("#chartContainer", 600, 400),
data = [
{ "cat": "W", "val": 123456789 },
{ "cat": "F", "val": 234567890 }
],
c = new dimple.chart(svg, data),
x = c.addCategoryAxis("x", "cat"),
y = c.addMeasureAxis("y", "val"),
s = c.addSeries(null, dimple.plot.bar);
// Append a row with no value for each x category you want
xValues.forEach(function (d) {
data.push({"cat": d})
}, this);
// Set the ordering as you did before
x.addOrderRule(xValues);
c.draw();
http://jsbin.com/hosobo/7/edit?js,output

Related

ggplot greek letter in label within for loop indices

I need to add the theta greek letter in the x-axis label of this plot(s):
var=c("a", "b", "c")
df=data.frame(x=c(1:20),y=c(41:60))
df_plot=list()
for (i in 1:length(var)) {
df_plot[[i]]=ggplot()+
geom_line(data=df, aes(x=x, y=y))+
xlab(paste("theta ", var[i]))
}
How can I do it?
If I use expression() I get the letter but not the index i.
Using bquote you could do:
Note: Instead of using a for loop I switched to lapply (and would suggest to so) as sooner or later you will run in issues related to tidy evaluation when using a for loop with ggplot. And there are plenty of questions on SO related to that. (:
var <- c("a", "b", "c")
df <- data.frame(x = c(1:20), y = c(41:60))
library(ggplot2)
lapply(var, function(x) {
ggplot() +
geom_line(data = df, aes(x = x, y = y)) +
xlab(bquote(theta*.(x)))
})
#> [[1]]
#>
#> [[2]]
#>
#> [[3]]

How to label the maximum point in a line chart using Maxima

How can I label the maximum point in a line chart using Maxima?
I have the code below in which I am plotting T(t):
draw2d(
xlabel = "t",
ylabel = "T",
explicit(ev(T), t, 0, 0.99));
However, I want to label in the chart, the point where t maximizes T. I solved the t that maximizes T as following:
opttr: diff(T,t,1)=0;
float(solve (opttr,t));
And I want this optimal t to be labeled in the Chart.
The full code can be found below.
kill(all);
assume(w >0);
assume(1- t >0);
N1:4;
N5:7;
w:5100;
p: (N1+ N5 + 5)*(1-t);
/* Enter the production function */
Y: 500*(N1+ N5 + 20)*L^(0.5);
/* Enter the profit function */
Profit: p*Y - w*L;
/* Calculate f.o.c */
eq1: diff(Profit,L,1) = 0;
float(solve (eq1,L));
L : rhs(%[1]);
/* Calculate tax revenue T(t) as a function of t */
T: t*p*ev(Y);
/* Find optimal tax */
opttr: diff(T,t,1)=0;
float(solve (opttr,t));
draw2d(
xlabel = "t",
ylabel = "T",
explicit(ev(T), t, 0, 0.99));

Pandas, groupby include number of rows grouped in each row

Have any way to use
df = pd.read_excel(r'a.xlsx')
df2 = df.groupby(by=["col"], as_index=False).mean()
Include new column with number of rows grouped in each row?
in absence of sample data, I'm assuming you have multiple numeric columns
can use apply() to then calculate all means and append len() to this series
df = pd.DataFrame(
{
"col": np.random.choice(list("ABCD"), 200),
"val": np.random.uniform(1, 5, 200),
"val2": np.random.uniform(5, 10, 200),
}
)
df2 = df.groupby(by=["col"], as_index=False).apply(
lambda d: d.select_dtypes("number").mean().append(pd.Series({"len": len(d)}))
)
df2
col
val
val2
len
0
A
3.13064
7.63837
42
1
B
3.1057
7.50656
44
2
C
3.0111
7.82628
54
3
D
3.20709
7.32217
60
comment code
def w_avg(df, values, weights, exp):
d = df[values]
w = df[weights] ** exp
return (d * w).sum() / w.sum()
dfg1 = pd.DataFrame(
{
"Jogador": np.random.choice(list("ABCD"), 200),
"Evento": np.random.choice(list("XYZ"),200),
"Rating Calculado BW": np.random.uniform(1, 5, 200),
"Lances": np.random.uniform(5, 10, 200),
}
)
dfg = dfg1.groupby(by=["Jogador", "Evento"]).apply(
lambda dfg1: dfg1.select_dtypes("number")
.agg(lambda d: w_avg(dfg1, "Rating Calculado BW", "Lances", 1))
.append(pd.Series({"len": len(dfg1)}))
)
dfg

Earley algorithm gone wrong

I am trying to implement Earley's algorithm for parsing a grammar, however I must have done something wrong because after the first entry in the chart it doesn't go through the rest of the input string. My test grammar is the following:
S -> aXbX | bXaX
X -> aXbX | bXaX | epsilon
S and X are non-terminals; a and b are terminals.
The string I want to check if it is accepted or not by the grammar is: 'abba'.
Here is my code:
rules = {
"S": [
['aXbX'],
['bXaX'],
],
"X" : [
['aXbX'],
['bXaX'],
['']
]
}
def predictor(rule, state):
if rule["right"][rule["dot"]].isupper(): # NON-TERMINAL
return [{
"left": rule["right"][rule["dot"]],
"right": right,
"dot": 0,
"op": "PREDICTOR",
"completor": []
} for right in rules[rule["right"][rule["dot"]]]]
else:
return []
def scanner(rule, next_input):
# TERMINAL
if rule["right"][rule["dot"]].islower() and next_input in rules[rule["right"][rule["dot"]]]:
print('scanner')
return [{
"left": rule["right"][rule["dot"]],
"right": [next_input],
"dot": 1,
"op": "SCANNER",
"completor": []
}]
else:
return []
def completor(rule, charts):
if rule["dot"] == len(rule["right"]):
print('completor')
return list(map(
lambda filter_rule: {
"left": filter_rule["left"],
"right": filter_rule["right"],
"dot": filter_rule["dot"] + 1,
"op": "COMPLETOR",
"completor": [rule] + filter_rule["completor"]
},
filter(
lambda p_rule: p_rule["dot"] < len(p_rule["right"]) and rule["left"] == p_rule["right"][p_rule["dot"]],
charts[rule["state"]]
)
))
else:
return []
input_string = 'abba'
input_arr = [char for char in input_string] + ['']
charts = [[{
"left": "S'",
"right": ["S"],
"dot": 0,
"op": "-",
"completor": []
}]]
for curr_state in range(len(input_arr)):
curr_chart = charts[curr_state]
next_chart = []
for curr_rule in curr_chart:
if curr_rule["dot"] < len(curr_rule["right"]): # not finished
curr_chart += [i for i in predictor(curr_rule, curr_state) if i not in curr_chart]
next_chart += [i for i in scanner(curr_rule, input_arr[curr_state]) if i not in next_chart]
else:
print('else')
curr_chart += [i for i in completor(curr_rule, charts) if i not in curr_chart]
charts.append(next_chart)
def print_charts(charts, inp):
for chart_no, chart in zip(range(len(charts)), charts):
print("\t{}".format("S" + str(chart_no)))
print("\t\n".join(map(
lambda x: "\t{} --> {}, {} {}".format(
x["left"],
"".join(x["right"][:x["dot"]] + ["."] + x["right"][x["dot"]:]),
str(chart_no) + ',',
x["op"]
),
chart
)))
print()
print_charts(charts[:-1], input_arr)
And this is the output I get (for states 1 to 4 I should get 5 to 9 entries):
S0
S' --> .S, 0, -
S --> .aXbX, 0, PREDICTOR
S --> .bXaX, 0, PREDICTOR
S1
S2
S3
S4

How to find duplicate elements in two different arrays

How do I find duplicate values in two different arrays ?
Pseudo-code:
array1["a", "b", "c", "d"]
array2["b", "d", "e", "f"]
duplicatesFound = findDuplicates(array1, array2) //will return ["b", "d"]
obviously there is more than one way to solve it, here is one:
You can use Intersect between two Iterable arrays. for example
val a1 = arrayListOf("a", "b", "c", "d")
val a2 = arrayListOf("b", "d", "e", "f")
val intersect = a2.intersect(a1)
Log.d(TAG,intersect.toString()) // prints [b,d]
Log.d(TAG,"${intersect.size}") // prints 2