Draw Raphael Donut Chart - svg

http://www.mediafire.com/view/z8ad4pedqr7twbl/donut.png
I want to draw this donut like that image. I have use raphaeljs for draw it. But I can't find the solution to make these borders with red and blue. Can someone help me? Is it possible or not?
My code below:
Raphael.fn.donutChart = function (cx, cy, r, rin, values, labels, stroke) {
var paper = this,
rad = Math.PI / 180,
chart = this.set();
function sector(cx, cy, r, startAngle, endAngle, params) {
//console.log(params.fill);
var x1 = cx + r * Math.cos(-startAngle * rad),
x2 = cx + r * Math.cos(-endAngle * rad),
y1 = cy + r * Math.sin(-startAngle * rad),
y2 = cy + r * Math.sin(-endAngle * rad),
xx1 = cx + rin * Math.cos(-startAngle * rad),
xx2 = cx + rin * Math.cos(-endAngle * rad),
yy1 = cy + rin * Math.sin(-startAngle * rad),
yy2 = cy + rin * Math.sin(-endAngle * rad);
return paper.path(["M", xx1, yy1,
"L", x1, y1,
"A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2,
"L", xx2, yy2,
"A", rin, rin, 0, +(endAngle - startAngle > 180), 1, xx1, yy1, "z"]
).attr(params);
}
var angle = 0,
total = 0,
start = 0,
process = function (j) {
var value = values[j],
angleplus = 360 * value / total,
popangle = angle + (angleplus / 2),
color = Raphael.hsb(start, .75, 1),
ms = 500,
delta = 30,
bcolor = "#ccc",
p = sector(cx, cy, r, angle, angle + angleplus, {fill:"#dfdfdf", "stroke-width":3, stroke:"red"}),
txt = paper.text(cx + (r + delta + 155) * Math.cos(-popangle * rad), cy + (r + delta + 150) * Math.sin(-popangle * rad), labels[j]).attr({fill:"#000", stroke: "none", opacity: 0, "font-size": 20});
p.mouseover(function () {
p.stop().animate({transform: "s1.25 1.25 " + cx + " " + cy}, ms, "elastic");
txt.stop().animate({opacity: 1}, ms, "elastic");
}).mouseout(function () {
p.stop().animate({transform: ""}, ms, "elastic");
txt.stop().animate({opacity: 0}, ms);
});
angle += angleplus;
chart.push(p);
chart.push(txt);
start += .1;
};
for (var i = 0, ii = values.length; i < ii; i++) {
total += values[i];
}
for (i = 0; i < ii; i++) {
process(i);
}
return chart;
};
var values = [],
labels = [];
$("tr").each(function () {
values.push(parseInt($("td", this).text(), 10));
labels.push($("th", this).text());
});
$("table").hide();
Raphael("holder", 700, 700).donutChart(350, 350, 80, 150, values, labels, "#fff");

You have to create separate paths if you want to stroke them differently:
var p = paper.path(["M", xx1, yy1,
"L", x1, y1,
"A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2,
"L", xx2, yy2,
"A", rin, rin, 0, +(endAngle - startAngle > 180), 1, xx1, yy1, "z"]
).attr(params);
paper.path(["M", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2]).attr({stroke: 'blue', 'stroke-width': 3});
paper.path(["M", xx2, yy2, "A", rin, rin, 0, +(endAngle - startAngle > 180), 1, xx1, yy1]).attr({stroke: 'red', 'stroke-width': 3});
return p;

Related

I need the algorithm for knapsack unbounded problem with atmost k number of repetitions for an item or weight

for example,
if i have weights=[20,10,30,40]
and values=[5,10,30,20]
and maximum weight that the bag
can store = 100
k=2, that is any weight can be
repeated atmost 2times.
The problem here is the values are profit percentages.
so the optimal answer for this
is (30 * 2) + (40 * 1), whose profit
is 2*(30 * 30/100) + 1 * (40*20/100) = 26.
Thanks in advance...
The solution is very easy.
Divide value by weight and call this R.
Sort the list according to R and value. i.e. where R is different, R is used. Where R is equal, value is used.
For your example, this results in:
w=[20,10,30,40], v=[5,10,30,20], r=[0.25, 1, 1, 0.5]
Then we sort it:
w=[30,10,40,20], v=[30,10,20,5], r=[1, 1, 0.5, 0.25]
Then we traverse w, and take up to 2 per index like below.
idx = 0, weight = 100, val = 0, ki = 0;
weight >= w[idx], weight -= w[idx], val += v[idx], ki++; // 0, 70, 30, 1
weight >= w[idx], weight -= w[idx], val += v[idx], ki++; // 0, 40, 60, 2
ki > k so increment index and reset ki. // 1, 40, 60, 0
weight >= w[idx], weight -= w[idx], val += v[idx], ki++; // 1, 30, 70, 1
weight >= w[idx], weight -= w[idx], val += v[idx], ki++; // 1, 20, 80, 2
ki > k so increment index and reset ki. // 2, 20, 80, 0
weight < w[idx], so increment idx // 3, 20, 80, 0
weight >= w[idx], weight -= w[idx], val += v[idx], ki++; // 3, 00, 85, 1
weight == 0, so terminate.
That would result in code that looks like:
for (int i = 0; i < weight.length; i++)
{
for (int j = 0; j < k; j++)
{
if (weight >= w[i])
{
weight -= w[i];
val += v[i];
}
else
{
break;
}
}
}

How alpha blending works with a transparent background in photoshop

I have two squares: red with color (255, 0, 0) 50% opacity, blue with color (0, 0, 255) 50% opacity
and black opaque background.
At the intersection of these colors, Photoshop shows the color (128, 0, 64) (
photoshp screenshot
).
And I agree whith that. Blue color first blends with black background:
(0, 0, 255) * 0.5 + (0, 0, 0) * ( 1 - 0.5) = (0, 0, 127.5)
alpha = 0.5 + 1 * (1 - 0.5) = 1
Then the result is mixed with red:
(255, 0, 0) * 0.5 + (0, 0, 127.5) * (1 - 0.5) = (127.5, 0, 63.75)
alpha = 0.5 + 1 * (1 - 0.5) = 1
But if background is transparent photoshop gives color (170, 0, 85) with 75% opacity (
photoshp screenshot
).
How does it get that color? I expected (127.5, 0, 127.5) with 75% opacity, because there is nothing in background to blend with.
Following the math described in this article, alpha blending blue square with 50% opacity onto the black background with 0% opacity results in this:
alpha_bg = 0
alpha_fg = 0.5
alpha_blended = alpha_fg + alpha_bg * (1 - alpha_fg) = 0.5
color_blended = ({0, 0, 255} * alpha_fg + {0, 0, 0} * (alpha_bg * (1 - alpha_fg))) / alpha_blended =
({0, 0, 255} * 0.5 + {0, 0, 0} * 0) / 0.5 = {0, 0, 255}
Then, repeating these calculations for blending the red square with 50% opacity on top of the color we calculated above:
alpha_bg = 0.5
alpha_fg = 0.5
alpha_blended = alpha_fg + alpha_bg * (1 - alpha_fg) = 0.5 + 0.5 * (1 - 0.5) = 0.75
color_blended = ({255, 0, 0} * alpha_fg + {0, 0, 255} * (alpha_bg * (1 - alpha_fg))) / alpha_blended =
({255, 0, 0} * 0.5 + {0, 0, 255} * (0.5 * (1 - 0.5))) / 0.75 = {170, 0, 85}

fragment shader skips part of coding

hi when i made my fragment shader coding i use:
---fragment
$HEADER$
void main(void)
{
float width = 0.0;
float offset = 0.1;
vec4 out_color = vec4(0, 0, 1, 1);
float coord = normalize(gl_FragCoord.x);
if (width == 0.0) {
vec4 out_color = vec4(0, 1, 1, 1);
}
else if (mod(((coord+offset) / width),2.0) < 0.3) {
vec4 out_color = vec4(0, 0, 0, 1);
}
gl_FragColor = out_color;
}
but when running the file with the vertex shader:
---vertex
$HEADER$
void main(void)
{
vec4 pos = vec4(vPosition.xy, 0.0, 1.0);
gl_Position = projection_mat * modelview_mat * pos;
}
and the python code:
from kivy.app import App
from kivy.base import EventLoop
from kivy.graphics import Mesh
from kivy.graphics.instructions import RenderContext
from kivy.uix.widget import Widged
w = 1000
h = 600
class GlslDemo(Widget):
def __init__(self, **kwargs):
Widget.__init__(self, **kwargs)
self.canvas = RenderContext(use_parent_projection=True)
self.canvas.shader.source = 'basic.glsl'
fmt = (
(b'vPosition', 2, 'float'),
)
vertices = (
0, 0,
w, 0,
w, h,
0, h,
)
indices = (0, 1, 2, 2, 3, 0)
with self.canvas:
Mesh(fmt=fmt, mode='triangles',
indices=indices, vertices=vertices)
class GlslApp(App):
def build(self):
EventLoop.ensure_window()
return GlslDemo()
if __name__ == '__main__':
GlslApp().run()
The problem when running this file is that it just outputs the vec4 out_color and skips the if and if else statements of the fragment shader code.
The variable out_color is declared 3 times in the fragment shader
1st in the scope of main
vec4 out_color = vec4(0, 0, 1, 1);
And another 2 times in the if statement:
if (width == 0.0) {
vec4 out_color = vec4(0, 1, 1, 1);
}
else if (mod(((coord+offset) / width),2.0) < 0.3) {
vec4 out_color = vec4(0, 0, 0, 1);
}
You have to assign to the variable which is declared in the scope of main, instead of declaring new variables in the if statement:
vec4 out_color = vec4(0, 0, 1, 1);
if (width == 0.0) {
out_color = vec4(0, 1, 1, 1);
}
else if (mod(((coord+offset) / width),2.0) < 0.3) {
out_color = vec4(0, 0, 0, 1);
}
Note, vec4 out_color; is a variable declaration, So vec4 out_color = vec4(0, 1, 1, 1); is an assignment to a new variabel, while out_color = vec4(0, 1, 1, 1); would assign to the existing variable out_color.

Animation is not working on a matplotlib gridspec

I have reviewed the answer to the question:
how to use GridSpec() with FuncAnimation in matplotlib?
however I believe I am doing something wrong but do not know what, my mission here is to create multiple animations for each of the grids and I also used a code mode for a gauge to animate the count of used data.
x1 = np.random.normal(-2.5, 1, 10000)
x2 = np.random.gamma(2, 1.5, 10000)
x3 = np.random.exponential(2, 10000)+7
x4 = np.random.uniform(14,20, 10000)
xrand = np.random.random(size = 10000)
x = [x1, x2, x3, x4]
plt.figure()
gspec = gridspec.GridSpec(3,3, wspace = 0.25)
GS1 = plt.subplot(gspec[0, 0])
GS2 = plt.subplot(gspec[0, 1])
GS3 = plt.subplot(gspec[1, 0])
GS4 = plt.subplot(gspec[1, 1])
GS5 = plt.subplot(gspec[0:,2:])
GS6 = plt.subplot(gspec[2,:2])
GS = [GS1, GS2, GS3, GS4, GS5, GS6]
bins1 = np.arange(-7.5, 2.5, 0.2)
bins2 = np.arange(0, 10, 0.2)
bins3 = np.arange(7, 17, 0.2)
bins4 = np.arange(12, 22, 0.2)
bins = [bins1, bins2, bins3, bins4]
axis1 = [-7.5, 2.5, 0, 0.6]
axis2 = [0, 10, 0, 0.6]
axis3 = [7, 17, 0, 0.6]
axis4 = [12, 22, 0, 0.6]
axis = [axis1, axis2, axis3, axis4]
GS1.hist(x1, bins = 1000)
GS2.hist(x2, bins = 1000)
GS3.hist(x3, bins = 1000)
GS4.hist(x4, bins = 1000)
GS5.scatter(x1, xrand, norm = True, c = 'r', s= 0.7)
GS5.scatter(x2, xrand, norm = True, c = 'g', s= 0.7)
GS5.scatter(x3, xrand, norm = True, c = 'b', s= 0.7)
GS5.scatter(x4, xrand, norm = True, c = 'y', s= 0.7)
for s in GS:
s.spines['right'].set_visible(False)
s.spines['top'].set_visible(False)
gspec.update(wspace = .6, hspace = .6)
fig, ((GS1,GS2),(GS3, GS4)) = plt.subplots(2, 2, sharey = True)
GS = [GS1, GS2, GS3, GS4]
def update(curr):
if curr == 500:
a.event_source.stop()
for i in range(0, len(GS)):
GS[i].hist(x[i][:curr], bins = bins[i], normed = True)
GS[i].axis(axis[i])
GS[i].gca().set_title('Sampling random distribution')
GS[i].gca().set_ylabel('Frequency')
GS[i].gca().set_xlabel('Value')
GS[i].annotate('n = {}'.format(curr), [3,27])
plt.tight_layout()
plt.show()
fig = plt.gcf()
a = animation.FuncAnimation(fig, update, interval = 10) #, blit = True, repeat = True)
I do not understand what is the problem with the code.
Problems:
You cannot use plt.show() inside the updating function.
GS[i].gca().set_title does not make sense, because GS[i] already is an axes, which does not have any gca() method. Same for set_ylabel and set_xlabel.
You need to call tight_layout() only once outside the loop.
You will need to remove the old histogram before plotting a new one on the axes.
Possibly the following is what you're after:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
x1 = np.random.normal(-2.5, 1, 10000)
x2 = np.random.gamma(2, 1.5, 10000)
x3 = np.random.exponential(2, 10000)+7
x4 = np.random.uniform(14,20, 10000)
xrand = np.random.random(size = 10000)
x = [x1, x2, x3, x4]
bins1 = np.arange(-7.5, 2.5, 0.2)
bins2 = np.arange(0, 10, 0.2)
bins3 = np.arange(7, 17, 0.2)
bins4 = np.arange(12, 22, 0.2)
bins = [bins1, bins2, bins3, bins4]
axis1 = [-7.5, 2.5, 0, 0.6]
axis2 = [0, 10, 0, 0.6]
axis3 = [7, 17, 0, 0.6]
axis4 = [12, 22, 0, 0.6]
axis = [axis1, axis2, axis3, axis4]
fig, ((GS1,GS2),(GS3, GS4)) = plt.subplots(2, 2, sharey = True)
GS = [GS1, GS2, GS3, GS4]
def update(curr):
if curr == 500:
a.event_source.stop()
for i in range(0, len(GS)):
GS[i].clear()
GS[i].hist(x[i][:curr], bins = bins[i], normed = True)
GS[i].axis(axis[i])
GS[i].set_title('Sampling random distribution')
GS[i].set_ylabel('Frequency')
GS[i].set_xlabel('Value')
GS[i].annotate('n = {}'.format(curr), [3,27])
plt.tight_layout()
fig = plt.gcf()
a = animation.FuncAnimation(fig, update, interval = 10)
plt.show()

Loop to change spring lengths doesn't change anything when I run it

The project I'm working on is supposed to model a pulse moving down a set of spheres connected by springs. I am trying to decrease the spring length as the pulse moves down the chain, but when I run it, nothing happens.
Here's my code:
from visual import *
one = sphere(pos=(-10,0,0), radius = 0.5, color = color.red)
two = sphere(pos=(-8,0,0), radius = 0.5, color = color.orange)
three = sphere(pos=(-6,0,0), radius = 0.5, color = color.yellow)
four = sphere(pos=(-4,0,0), radius = 0.5, color = color.green)
five = sphere(pos=(-2,0,0), radius = 0.5, color = color.blue)
six = sphere(pos=(0,0,0), radius = 0.5, color = color.cyan)
seven = sphere(pos=(2,0,0), radius = 0.5, color = color.magenta)
eight = sphere(pos=(4,0,0), radius = 0.5, color = color.white)
nine = sphere(pos=(6,0,0), radius = 0.5, color = color.red)
ten = sphere(pos=(8,0,0), radius = 0.5, color = color.orange)
spring1 = helix(pos = (-10, 0, 0), length = 2, radius = 0.3,
thickness = 0.05, color = color.red)
spring2 = helix(pos = (-8, 0, 0), length = 2, radius = 0.3,
thickness = 0.05, color = color.orange)
spring3 = helix(pos = (-6, 0, 0), length = 2, radius = 0.3,
thickness = 0.05, color = color.yellow)
spring4 = helix(pos = (-4, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.green)
spring5 = helix(pos = (-2, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.blue)
spring6 = helix(pos = (0, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.cyan)
spring7 = helix(pos = (2, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.magenta)
spring8 = helix(pos = (4, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.white)
spring9 = helix(pos = (6, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.red)
masses = [one, two, three, four, five, six, seven, eight, nine, ten]
springs = [spring1, spring2, spring3, spring4, spring5, spring6, spring7,
spring8, spring9]
while True:
n=0
deltax=.2
while n < 10:
rate(30)
masses[n].pos.x = masses[n].pos.x + deltax
if n < 9:
springs[n].pos = masses[n].pos
springs[n].axis = masses[n+1].pos-masses[n].pos
n=n+1
n = n-1
while n >= 0:
rate(30)
masses[n].pos.x = masses[n].pos.x - deltax
if n < 0:
springs[n-1].pos = masses[n-1].pos - deltax
springs[n-1].axis = masses[n].pos-masses[n-1].pos
n = n-1
while True:
m=0
deltat=.2
while m<9:
rate(30)
springs[m].length = springs[m].length - deltat
springs[m].length = springs[m].length + deltat
m=m+1
m=m-1
while n>=0:
rate(30)
springs[m].length = springs[m].length - deltat
springs[m].length = springs[m].length + deltat
m=m-1
Make the masses have opacity = 0.3 and replace the first rate statement with scene.waitfor('click'). You'll see that when you move the nth mass to the right, the spring does in fact shorten, and when the (n+1)th mass is moved, the spring to its right shortens, leaving a gap between the nth spring and the (n+1)th spring.
Incidentally, I don't understand where there is a second "while True". It will never be reached.
I'll advertise that a better place to pose VPython questions is in the VPython forum at
https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users

Resources