How to subdivide the space inside a small multiple - r

I need to create small multiples (like the one shown in the picture) using ggplot2 where each circle occupies 70% of the total size of it's own small multiple and the remaining 30% is empty space.
I know the center and the radius of the circle.
Question: Is it possible to do this, and if so, how?

Area of ​​a circle = C = π * r²
Area of your square = S = width * length = side²
So just calculate C, so you can calculate how big S must be to fullfill your criteria. When you know S you know the side, which translates to how you have to set the axis limits for x and y.

Related

Bokeh circle height is incorrect [duplicate]

I am plotting some geometry using bokeh and came across this. I am plotting a rectangle with equal sides (i.e. a square), and in that square, plotting a circle with diameter = width of the square. The circle should tangent to the square at edges, but it is not.
here is the code:
from bokeh.plotting import output_notebook, figure, show
output_notebook()
p = figure(width=500, height=500)
p.rect(0, 0, 300, 300, line_color='black')
p.circle(x=0, y=0, radius=150, line_color='black',
fill_color='grey', radius_units='data')
p.axis.minor_tick_out = 0
show(p)
Which results in this:
Is there anything I am doing wrong or could change to make the circle fit exactly in the square?
Thanks in advance,
Randall
Here's another case - just drawing a circle:
p = figure(width=500, height=500, x_range=(-150, 150), y_range=(-150, 150))
p.circle(x=0, y=0, radius=150, line_color='black',
fill_color='grey', radius_units='data')
show(p)
radius of the circle is 150 in the x direction, but not the y-direction.
I would like to report that as of Bokeh 0.12.7, this issue can now be fixed in a simpler manner.
As described in other posts, the main issue is not that the circle is not a circle, but that the square is not a square. This is due to the fact that actual area on which Bokeh draws the figure (the canvas) is usually not a square by default or even when the width and height are set to the same value. Bokeh by default will attempt to draw a figure by using up all the space on the canvas. This creates a mismatch between the data distance and the pixel distance of the plot.
As of 0.12.7, figures can now accept a match_aspect property which when set to True will will match the aspect of the data space to the pixel space of the plot.
In your example, simply adding the match_aspect = True in your figure
p = figure(width=500, height=500, match_aspect=True,
title="Circle touches all 4 sides of square")
p.rect(0, 0, 300, 300, line_color='black')
p.circle(x=0, y=0, radius=150, line_color='black',
fill_color='grey', radius_units='data')
will now produce
UPDATE: Please note new answer by #DuCorey below. As of Bokeh 0.12.7, aspect control is now available, for situations like this.
The issue is actually that the square is not square, and that is because the pixel aspect ratio and the "data" aspect ratio do not match. i.e., the distance per pixel is different in the x direction than it is in the y direction.
There are a few options:
You can use various properties to control the dimensions of the central plot area (e.g. plot border width and axis tick label orientation) You can also control you data ranges explicitly. In other words, you can make the aspect ratios match, and then the circle and rect will match
You can use absolute pixel units (e.g. size for a circle, and use a large square marker instead of rect) instead of "data" units.
Alternatively, if you want a circle that "deforms" when the aspects do not match, then your best bet is to use an ellipse with an identical width and height, which will work because in this case bokeh has two dimensions to use to measure (instead of the single radius) and can match each to the scale along each dimension independently.
(This is actually the fundamental difference that explains the behaviour: rect has two dimensions to measure independently. circle does not, it only has one, and has to arbitrarily use the x or y dimension to measure distance per pixel)
ok, based on the suggestions, I tried a few things.
Changed the orientation of the y-axis tick labels - still
had issue.
Changed various stand-offs, even moving in the tick
labels inside the plot (with a negative offset). Did not work either.
Changed the x_range and r_range in figure() to be equal tuples. Did not work either
Changes the plot_height (decreased it), and I could eventually, through rial and error, get the circle to fit in the square with a plot_height that was < plot width.
Lots of great practice controlling attributes of the plot. Time will invested.
However, the last change I tried worked the best. It was one of the first suggestions - change the plot border.
Weirdly, setting p.min_border=40, which on 0.12.6 is the default value, and voila, it appears the chart aspect ratio for a chart where plot_width=plot_height is truly 1 on the screen as well.
p = figure(plot_width=500, plot_height=500)
p.rect(0, 0, 300, 300, line_color=None)
p.circle(x=0, y=0, radius=150, line_color=None,
fill_color='lightgrey', radius_units='data')
p.min_border=40
show(p)
Before and after images showing the effect of adding p.min_border=40. Any value over ~33 appeared to be enough force the plot area to have the same screen x and y dimension - so the square was really a square (and the circle fit inside).
The reason for this is that you're creating a circular marker (or circle glyphs) and placing it at position (0, 0), while it seems like you want to create a circle centered at 0.
I think the rect here "happens" to work because it can scale correctly in both dimensions and remain a "rectangle".
Keyword Args:
radius (UnitsSpecPropertyDescriptor) : The radius values for circle markers (in "data space" units, by default). (default None)
radius_dimension (BasicPropertyDescriptor) : What dimension to measure circle radii along. (default 'x')
radius_units (Enum('screen', 'data')) : (default 'data')
I guess my point is here you've taken a shortcut by trying to use a "glyph" as your plot and specifying the units to be the data units.
If you want to create an actual circle you could do the following:
th = np.linspace(0, 2*np.pi)
r = 150
p = figure(width=500, height=500)
p.rect(0, 0, 300, 300, line_color='black')
p.line(r * np.cos(th), r * np.sin(th), line_color='black')
# p.circle(x=0, y=0, radius=150, line_color='black',
# fill_color='grey', radius_units='data')
p.axis.minor_tick_out = 0
show(p)
Notice the above is harder to fill (I didn't bother) because I'm guessing you need to define some closed polygon function while I only defined a line that happens to be a closed polygon, in this case a circle.
Not sure, but the bleu rectangle is not your rectangle.
Replace:
p.rect(0, 0, 300, 300, line_color='black')
By:
p.rect(-150, -150, 150, 150, line_color='black')

Calculating the angle tilt using only accelerometers

I would like to know how to calculate using the coordinates of the accelerometer of my Android phone the angle between the two segments connecting the accelerometer and the bottom of the tree (B) and the accelerometer and the top of the tree (T) .
The accelerometer takes a value of acceleration on 3 axes every second, so I calculated the average and I have:
For the phone towards B: Ay1 = -9.69m.s^-1 and Az1 = 0.71m.s^-1
For the phone towards T: Ay2 = -9.71m.s^-1 and Az2 = 0.71m.s^-1
I am located at a distance D = 20m from the tree.
I would like at the end to know the value of H. So I would like to know how to calculate the angle and then find the height of the tree.
Thanks for your help
The angles we need are the angles between world-up and device-up. Since the gravity vector is pointing towards world-down, this is simply (assuming, you are pointing with the device y-axis):
cos angle = -a.y / sqrt(a.x^2 + a.y^2 + a.z^2)
The two angles we get from your readings are:
angle1 = 4.19065°
angle2 = 4.18205°
You can already see that the angles are very close as the two acceleration values are also extremely close. Btw, I wonder if you are really pointing with the y-axis because the gravity values suggest that you are holding the phone almost upright in both cases.
Anyway, if we assume that the two angles are correct, we can now calculate the height of the respective triangles assuming a length to target l. Then:
tan (90° - angle) = h / l
Assuming l=20 m, this gives us two height values:
h1 = 272.958 m
h2 = 273.521 m
These are heights above the height of the phone. In theory, one should be positive and the other should be negative. The height of the tree would be the difference of the two heights:
treeH = h2 - h1
treeH = 0.56338 m
As you have seen throughout the example, your readings must be pretty off. Nevertheless, this is how you would calculate the tree height.

One-point perspective and point with negative depth

I am trying to create a game using one-point perspective. Everything works fine for points within the view but goes wrong with the negative depth. I understand the perspective as shown on the following picture (source).
In general, I took a point at some distance from the left of the right vertical edge of the frame along the lower horizontal line (5 points in this case), join it with the O' point (line H'O') and where the line intersects the vertical line (at point H') is the depth line (of 5 in this case). This works well even for negative depth (as the line H'O' intersect the vertical line below the viewpoint). However, if the depth is more then is the distance of O' (that mean the point would be on the right from the O') the line flip and the H' end on top of the viewpoint (although it should end up below).
How should I correct it, so the point with negative depth is transformed correctly (mean from 3D space to 2D space)?
EDIT
This image is probably better.
My question is how to handle points with negative depth (should end up below the screen) higher then is a distance of transversal.
The points to the right of the point O', along the line determined by the lower edge of the frame, correspond to points that are behind the observer, so technically, the observer cannot see them. To see the points behind you, means that you have to turn around, so you need to change the position of the screen. Draw a copy of the black square frame to the right of the point O', so that the new square is the mirror symmetric image of the original frame square with respect to the line orthogonal to the horizon line and passing trough the point O'.
Edit: The points with negative depth to the right of point O' (i.e. a point behind the observer) is supposed to be mapped above the horizontal blue line. This is the right way to go.
I assume your coordinate system in three dimensions has its origin at the lower right corner of the square frame on your picture. The x axis (I think how you measure width) runs along the lower horizontl edge of the frame, while the y axis (what you call height) is along the right vertical edge of the frame. The depth axis is in three dimensions and it's perpendicular to the plane of the square frame (so it is parallel to the ground). It starts from the lower right corner of the frame square. Assume that the distance of point O' from the right vertical edge of the square is S and the coordinates of the point C are {C1, C2} (C1 is the distance of point C from the right vertical edge and C2 is the distance of C from the lower horizontal edge of the square).
Given the coordinates {w, h, d} (w - width, h - height, d - depth) of a point in three dimensions, its representation on the two dimesnional square screen is gievn by the formulas:
x = (S*w + C1*d)/(S+d)
y = (S*h + C2*d)/(S+d)
So the points you gave as an example in the comments are
P1 = {h = 5, w = 5, d = 5} and P2 = {h = 5, w = 5, d = -10}
Their representation on the screen is
P1_screen = {(S*5 + C1*5)/(S+5), (S*5 + C2*5)/(S+5)}
P2_screen = {(S*5 - C1*10)/(S-10), (S*5 - C2*10)/(S-10)}
whatever your parameters S, C1 and C2 are. The representation of the (infinte) line connecting points P1 and P2 is represented on the screen as the (infinite) line connecting the points P1_screen and P2_screen. However, if you want the 2D representation of the visible part of the segment that connects P1 and P2, then you have to draw the (infinite) line between P1_screen and P2_screen and exclude the following two segment: segment [P1_screen, P2_screen] and the segment from P2_screen along the line up towards the upper top edge. You have to draw on the screen only the segment from the infinite line connecting P1_screen and P2_screen which starts from P1_Screen and goes down towards the lower horizontal edge of the screen.

Filling a grid with boxes with numbers with decreasing size

There is this interesting game, that has numbers in a grid, where each number has progressively smaller font. The player's task is to click on the numbers in succession.
I'm interested in the algorithm that creates the boxes for the numbers, I cannot think of a way it works.
Apparently the grid has N numbers (apart from the 1.88 in the picture), number 1 has the biggest font and succesively the font size decreases. Then the numbers are somehow placed on the grid and boxes grow around them. But it doesn't seem totally random, as there are some horizotal lines that go across the whole grid.
Do you have an idea on how this might work?
It looks to me as though the boxes have been generated by successive division. That is, starting with the full rectangle, a dividing line (horizontal or vertical) was placed, and then the two resulting rectangles were subdivided in turn, until there were enough rectangles for the game.
Here's a sketch of the first algorithm I would try. N is the number of rectangles I want to divide the original rectangle into, and A is a critical aspect ratio used to stop the small rectangles getting too narrow. (Perhaps A = 1.5 would be a good start.)
Create an empty priority queue and add the full rectangle to it.
If the length of the priority queue is greater than or equal to N, stop.
Remove the largest rectangle, R, from the priority queue.
Choose whether to divide it horizontally or vertically: if its aspect ratio (width/height) is greater than A, divide it vertically; if less than 1/A, divide it horizontally, otherwise choose at random.
Decide where to put the dividing line. (Perhaps randomly between 40% and 60% along the chosen dimension.)
This divides R into two smaller rectangles. Add both of them to the priority queue. Go to step 2.
When this algorithm completes, there are N rectangles in the queue. Put the number 1 in the largest of them, the number 2 in the second largest, and so on.
It turns out that putting the numbers into the boxes is not quite as straightforward as I assumed in my first attempt. The area metric works well for subdividing the rectangles nicely, but it doesn't work for putting the numbers into the boxes, because for fitting text into a box, the height and width both have to be taken into account (the area is not so useful).
Instead of explaining the algorithm for putting numbers into the boxes, I will just give you some sample code in Python and let you reverse-engineer it!
import heapq, itertools, random
import Image, ImageDraw, ImageFont
# ALGORITHM PARAMETERS
aspect_max = 1.5 # Above this ratio, always divide vertically
aspect_min = 1.0 # Below this ratio, always divide horizontally
div_min = 0.4 # Minimum position for dividing line
div_max = 0.6 # Maximum position for dividing line
digit_ratio = 0.7 # Aspect ratio of widest digit in font
label_margin = 2 # Margin around label (pixels)
class Rectangle(object):
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
self.area = self.w * self.h
self.aspect = float(self.w) / self.h
def __le__(self, other):
# The sense of this comparison is inverted so we can put
# Rectangles into a min-heap and be able to pop the largest.
return other.area <= self.area
def __repr__(self):
return 'Rectangle({0.x}, {0.y}, {0.w}, {0.h})'.format(self)
def divide(self, n):
"""
Divide this rectangle into `n` smaller rectangles and yield
them in order by area (largest first).
"""
def division(l):
return random.randrange(int(l * div_min), int(l * div_max))
queue = [self]
while len(queue) < n:
r = heapq.heappop(queue)
if (r.aspect > aspect_max
or r.aspect > aspect_min
and random.random() < 0.5):
# Vertical division
w = division(r.w)
heapq.heappush(queue, Rectangle(r.x, r.y, w, r.h))
heapq.heappush(queue, Rectangle(r.x + w, r.y, r.w - w, r.h))
else:
# Horizontal division
h = division(r.h)
heapq.heappush(queue, Rectangle(r.x, r.y, r.w, h))
heapq.heappush(queue, Rectangle(r.x, r.y + h, r.w, r.h - h))
while queue:
yield heapq.heappop(queue)
def font_height(self, n):
"""
Return the largest font height such that we can draw `n`
digits in this rectangle.
"""
return min(int((self.w - label_margin * 2) / (digit_ratio * n)),
self.h - label_margin * 2)
def draw_rectangles(rectangles, fontfile):
"""
Create and return an Image containing `rectangles`. Label each
rectangle with a number using the TrueType font in `fontfile`.
"""
rectangles = list(rectangles)
im = Image.new('RGBA', (1 + max(r.x + r.w for r in rectangles),
1 + max(r.y + r.h for r in rectangles)))
draw = ImageDraw.Draw(im)
for digits in itertools.count(1):
rectangles = sorted(rectangles,
key = lambda r: r.font_height(digits),
reverse = True)
i_min = 10 ** (digits - 1)
i_max = 10 ** digits
i_range = i_max - i_min
for i in xrange(i_range):
if i >= len(rectangles): return im
r = rectangles[i]
draw.line((r.x, r.y, r.x + r.w, r.y, r.x + r.w, r.y + r.h,
r.x, r.y + r.h, r.x, r.y),
fill = 'black', width = 1)
label = str(i + i_min)
font = ImageFont.truetype(fontfile, r.font_height(digits))
lw, lh = font.getsize(label)
draw.text((r.x + (r.w - lw) // 2, r.y + (r.h - lh) // 2),
label, fill = 'black', font = font)
rectangles = rectangles[i_range:]
Here's a sample run:
>>> R = Rectangle(0, 0, 400, 400)
>>> draw_rectangles(R.divide(30), '/Library/Fonts/Verdana.ttf').save('q10009528.png')
The pattern of the cuts looks recursive. That is, the process of dividing the region into rectangles consists of cutting a rectangle in two, over and over. There are two cuts that divide the whole rectangular region (the horizontal cuts above and below 1), so we can't tell which cut came first, but we see the cuts as a kind of tree: the cut that separates 1 from 10 produced a large rectangle below it (20, 21, 4, 10, etc.), which was then divided by the vertical cut between 21 and 4, the rectangle containing 4 was later divided by the cut that separates 4 and 14, and so on. There are N cuts that produce N regions plus one leftover ("1.88") which is not necessary but which might give us a clue.
Now we just have to figure out the order of the cuts, the choice of proportion and the choice of orientation.
Consecutive numbers are rarely neighbors, so it looks as if numbers are not assigned as the cutting progresses. Instead, the region is chopped into rectangles, the rectangles are sorted by size and then numbers are assigned (notice that 20 and 21 are neighbors, but they were formed by other cuts after the one that divides them).
A plausible hypothesis for the order of the cuts is that the algorithm always cuts the largest rectangle. If that were not true, we might see, e.g., 14 bigger than 15 and 18 combined, and I see no example of that.
Proportion... With careful measurement we could see the actual distribution of proportions, but I don't feel like doing that much work. We see no very long, thin rectangles and no 50/50 cuts, so at a guess I'd say the algorithm chooses randomly, in some range like [0.6, 0.8]. Maybe it tries to avoid making a rectangle very close to the size of a rectangle that already exists. After all the cuts, the rectangle chosen to be left over ("1.88") is neither the biggest nor the smallest; maybe it's random, maybe it's the second-biggest, maybe it's something else-- more examples would be useful.
The orientation seems to be strongly biased towards cutting rectangles across their narrow width, rather than "lengthwise". This has the effect of producing rectangles more like squares and less like books on a shelf. The only possible exception I can see is the 1-9 cut, which might divide the block whose lower-right number is 1 lengthwise. But that depends on the order of cuts above and below 1, so it leads to a hypothesis: the algorithm always cuts a rectangle along its shorter dimension, and the 1-9 cut was actually the first.
That's about as far as I can go, short of breaking out a ruler and calculator.

how to measure the distance in dicom

I want to know how to measure the distance between two pixels in dicom . already done some google found pixel spacing (0028,0030) need to find the distance . could some one clearly explain ....
thanks
Assuming that you're trying to measure distances in the subject/animal/phantom/whatever, it all depends on whether you want to measure distances between different slices or just in the same slice.
Volumetric DICOM series typically have a slice spacing (0012,0088) in addition to the pixel spacing which you need to take into account. Note that there is also such a thing as slice thickness, which is distinct and should not be used for calculating distances, as there can be a gap or overlap between consecutive slices.
It is helpful to define a voxelspacing vector as follows (pseudocode):
voxelspacing.x = first element of PixelSpacing (0028,0030), i.e. before "\"
voxelspacing.y = second element of PixelSpacing (0028,0030), i.e. after "\"
voxelspacing.z = SliceSpacing (0018,0088) or 0 if 2D and/or not specified
Some brain-dead manufacturers and de-identification tools break the slice spacing tag in which case you'll have to calculate it from another source, such as difference in consecutive slice location, patient image position, etc, but that's another matter.
Moving on, you now have the distance in millimeters between voxels for each dimension. You can then calculate the real-world euclidean distance given voxel coordinates in pointA and pointB:
delta = (pointA - pointB) * voxelspacing
distance = sqrt(delta.x^2 + delta.y^2 + delta.z^2);
Where all the operators are element-wise. It is critical to individually multiply the voxel coordinates with their respective spacings before computing distance, because voxels are typically not isotropic.
You need to know the dot pitch of the monitor. For example a jumbotron has huge pixels (guessing), so the distance is larger than it would be for a typical desktop monitor. Ask the manufacturer of the monitor for this information. After that use pythogorean theorum. sqrt(a^2 + b^2) = c c being the total distance and a/b are x and y distances. to find a and be you would find the coordinates of one pixel and subtract from the other. a = (x1-x2) b = (

Resources