i've written program calculates line of best fit (intercept/slope) given several input values user. i've plotted each of individual values, unsure of code plot line given slope , y-intercept.
this slope:
double m = ( axy.sum() - ((levels.sum() * scores.sum()) / 5)) / (newax.sum() - ((powlevels) / 5));
the intercept
double b = meany - (m * meanx);
plotting of points
for (int = 0; < levels.getlength(0); i++) { chart1.series["series1"].points .addxy(levels.getvalue(i), scores.toarray().getvalue(i)); }
any ideas? no means expert , getting far took fair bit of experimenting..
assuming data plotted scattergraph using charttype.points
simplest way add line add 1 extra series
charttype.line
, set 2 points there.
there are other ways create line on chart
, drawing or creating lineannotation
, much more complicated!
following this example letter here implementation:
note after creating series line of best fit thing looking last 2 lines..:
private void button1_click(object sender, eventargs e) { // create 2 series! chart1.series.clear(); chart1.series.add("data"); chart1.series.add("line of best fit"); chart1.series[0].charttype = seriescharttype.point; chart1.series[1].charttype = seriescharttype.line; list<int> levels = new list<int>() { 8, 2, 11, 6, 5, 4, 12, 9, 6, 1}; list<int> scores = new list<int>() { 3, 10, 3, 6, 8, 12, 1, 4, 9, 14}; double minx = levels.tolist().min(); double maxx = levels.tolist().max(); double meanx = 1f * levels.sum() / levels.count; double meany = 1f * scores.sum() / scores.count; double st = 0; double sb = 0; (int = 0; < levels.count; i++ ) { st += (levels[i] - meanx) * (scores[i] - meany); sb += (levels[i] - meanx) * (levels[i] - meanx); } double slope = st / sb; double y0 = meany - slope * meanx; // y-intercept or y-crossing (int = 0; < levels.count; i++) { chart1.series[0].points.addxy(levels[i], scores[i]); } // part creates line of best fit: chart1.series[1].points.addxy(minx, y0 + minx * slope); chart1.series[1].points.addxy(maxx, y0 + maxx * slope); }
if want can add first line point right @ y-axis:
chart1.series[1].points.addxy(0, y0 );
in case may want set minimum x-values shown in chart prevent including -1
, maybe this:
chart1.chartareas[0].axisx.minimum = minx - 1;
Comments
Post a Comment