does anybody know how to plot the Dirac function in top left corner and the sinus function given in the picture. I managed to plot the second and third easily. Would you do this with a piecewise function or is there an easy way for Plot #1 and #4 ? Thank you very much!
Arbitrary Excitations
If this is homework then I suppose that for the sinus example you are being asked to investigate the effects of scale and shift.
Consider these plots, one after another. Observe how they differ. First I scale the magnitude (y-direction) by 10. Then I scale in the x-direction. And finally I shift in the x-direction.
plots:-setoptions(size=[300,0.6],tickmarks=[decimalticks,default]):
plot( 10*sin( x ), x=0 .. Pi, view=[0..Pi, 0..18] );
plot( 10*sin( x*Pi ), x=0 .. 1, view=[0..1, 0..18] );
plot( 10*sin( x*Pi/0.3 ), x=0 .. 0.3, view=[0..1, 0..18] );
plot( 10*sin( (x-0.1)*Pi/0.3 ), x=0.1 .. 0.4, view=[0..1, 0..18] );
plots:-setoptions();
It can be made to look similar to the 4th plot in the image to which you linked quite easily. You can try it with and without the various options.
P:= plot( 10*sin( (x-0.1)*Pi/0.3 ), x=0.1 .. 0.4
, axes=none
, color=black
, size=[300,0.7]
, thickness=2
):
plots:-display( P
, view=[0.0 .. 0.6, 0..18]
, tickmarks=[[0.1,0.4],[10=10*N]]
, axes=normal, labels=[`t[s]`,`F(t)`]
, size=[300,0.6]
);
And with more effort it can be made a closer match, visually.
plots:-display( P
, plottools:-arrow([0,0],[0.6,0], 0.05, 0.9, 0.05)
, plottools:-arrow([0,0],[0,16], 0.001, 0.02, 0.08)
, plots:-textplot([0.6, -3.5, `t[s]`, font=["courier",16]])
, plots:-textplot([0.0, 18, `F(t)`, font=["courier",16]])
, seq(plots:-textplot([X, -1.5, X]), X=[0,0.1,0.4])
, plots:-textplot([-0.05, 10, "10 N"])
);
For your other plot you could simply plot a sequence of lines.
T:=table([1=60,2=100,3=0,4=20]):
P2:=seq(plottools:-line([i,0],[i,T[i]],thickness=2,color=black),
i=1..4):
And you could adjust the look and feel of the final plot as above. I'll leave that to you.
plots:-display(P2
, size=[300,0.7]
, view=[0..6, 0..120]
, labels=["",""]
);
Related
When I plot single images they appear to be skewed, but doesn't appear that way when I look at the images in 3DSlicer or another viewer. I'm not sure if there's something I should be adjusting that I'm not aware of. The below is how I converted from DICOM:
dicom2nifti.convert_directory(path_to_dicom_before, path_to_dicom_before_converted, compression=True, reorient=True)
dicom2nifti.convert_directory(path_to_dicom_post, path_to_dicom_post_converted, compression=True, reorient=True)
print(glob(path_to_dicom_before_converted + '*.nii.gz'))
nii_before = nib.load(glob(path_to_dicom_before_converted + '*.nii.gz')[0])
nii_after = nib.load(glob(path_to_dicom_post_converted + '*.nii.gz')[0])
nii_before_data = nii_before.get_fdata()
nii_after_data = nii_after.get_fdata()
fig, ax = plt.subplots(figsize=[10, 5])
plotting.plot_img(nii_before, cmap='gray', axes=ax)
plt.show()
fig, ax = plt.subplots(figsize=[10, 5])
plotting.plot_img(nii_after, cmap='gray', axes=ax)
plt.show()
plt.imshow(nii_before_data[100], cmap='bone')
plt.axis('off')
plt.show()
Affine of the first:
[[-3.19454312e-01 7.17869774e-02 3.95075195e-02 6.01478424e+01]
[ 5.83867840e-02 2.97792435e-01 -2.28872180e-01 1.27874863e+02]
[ 4.69673797e-02 1.18071720e-01 5.53225577e-01 1.12181287e+03]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.00000000e+00]]
As you can see in this answer you are plotting the row 100 with all columns and all slices! Also you need to plot the pixel array nii_before_data and not the whole Nifti image nii_before which contains other types of data.
you can try:
nii_before = nib.load(glob(path_to_dicom_before_converted + '*.nii.gz')[0])
nii_after = nib.load(glob(path_to_dicom_post_converted + '*.nii.gz')[0])
nii_before_data = nii_before.get_fdata()
nii_after_data = nii_after.get_fdata()
## Same goes for nii_after_data
if(len(nii_before_data.shape)==3):
for slice_Number in range(nii_before_data.shape[2]):
plt.imshow(nii_before_data[:,:,slice_Number ])
plt.show()
if(len(nii_before_data.shape)==4):
for frame in range(nii_before_data.shape[3]):
for slice_Number in range(nii_before_data.shape[2]):
plt.imshow(nii_before_data[:,:,slice_Number,frame])
plt.show()
If you can provide a sample Nifti Image the solution might be more precise according to your data.
I'd like to define line styles in Octave (like in gnuplot) for further usage:
I was thinking about something like that:
styles = {['color',[.5 .2 .8],'--', 'linewidth', 1.25], ['or', markersize, 4],
['-sb', markersize, 2]}
plot (x,y, styles{1})
plot (x,y, styles{2})
and so on. But such a thing didn't work. Does someone have any suggestions how to solve this?
Thanks in advance.
Let's have a look, what MATLAB does and copy the ideas: You can use Comma-Separated Lists as Function Call Arguments. Actually, there's an example describing exactly, what you want to achieve. Nevertheless, to get this working as you'd like to, you also have to "disassemble" the LineSpec properly. Please see the following code snippet to get the solution for the examples given by you.
x = linspace(0, 2*pi, 50);
% styles = {['color',[.5 .2 .8],'--', 'linewidth', 1.25], ['or', markersize, 4], ['-sb', markersize, 2]}
styles = {
{'Color', [.5 .2 .8], 'LineStyle', '--', 'LineWidth', 1.25}, ...
{'Color', 'r', 'Marker', 'o', 'MarkerSize', 4}, ...
{'Color', 'b', 'LineStyle', '-', 'Marker', 's', 'MarkerSize', 2} ...
};
figure(1);
hold on;
for ii = 1:numel(styles)
plot(x, sin(x + ii * pi/4), styles{ii}{:});
end
hold off;
legend();
And, here is an exemplary output:
Ok So I have looked at a couple of different questions on here but I haven't been able to find anything to help to solve this problem. I split up 303 lines with 13 rows in them between healthy patients and sick patients. I was able to get the averages of both but now I need to get the median of those 2 averages (to make things clear this is what the output should look like).
Averages of Healthy Patients:
[52.59, 0.56, 2.79, 129.25, 242.64, 0.14, 0.84, 158.38, 0.14, 0.59, 1.41, 0.27, 3.77, 0.00]
Averages of Ill Patients:
[56.63, 0.82, 3.59, 134.57, 251.47, 0.16, 1.17, 139.26, 0.55, 1.57, 1.83, 1.13, 5.80, 2.04]
Seperation Values are:
[54.61, 0.69, 3.19, 131.91, 247.06, 0.15, 1.00, 148.82, 0.34, 1.08, 1.62, 0.70, 4.79, 1.02]
I have tried different methods for trying to get the median but I have failed on all my attempts so I've officially run out of ideas of how to get it. So if you can look and see if maybe I was on the right track and just missed something small or am completely way off I would appreciate any insight on this problem.
ill_avg = [ill / len(iList) for ill in iList_sum]
hlt_avg = [ hlt / len(hList) for hlt in hList_sum]
median = [(b / len(bList) for b in bList_sum) //2 ]
print('Total of lines Processed: ' + str(numline))
print("Total Healthy Count: " + str(HPcounter))
print("Total Ill Count: " + str(IPcounter))
print("Averages of Healthy Patients:")
print(str(hlt_avg))
print("Averages of Ill Patients ")
print('[' + ', '.join(['{:.2f}'.format(number) for number in ill_avg]) + ']')
print("Seperation Values are:")
print(median)
tried to get the median by adding both averages but I couldn't get it to work and my latest try was to makes a solo average(bList which is all patients) and get the median in that. If I can make the first way work without the bList I would prefer it that way since it will make the code less redundant and hopefully smaller.
I apologize I forgot to mention I am not suppose to use numpy or panda since we have not gone over those 2 in class yet.
Use numpy:
import numpy
a = numpy.array([[52.59, 0.56, 2.79, 129.25, 242.64, 0.14, 0.84, 158.38, 0.14, 0.59, 1.41, 0.27, 3.77, 0.00],
[56.63, 0.82, 3.59, 134.57, 251.47, 0.16, 1.17, 139.26, 0.55, 1.57, 1.83, 1.13, 5.80, 2.04]])
print numpy.mean(a, axis=0)
or use pure Python if you have to avoid numpy:
from __future__ import division
def mean(a):
return sum(a) / len(a)
a = [[52.59, 0.56, 2.79, 129.25, 242.64, 0.14, 0.84, 158.38, 0.14, 0.59, 1.41, 0.27, 3.77, 0.00],
[56.63, 0.82, 3.59, 134.57, 251.47, 0.16, 1.17, 139.26, 0.55, 1.57, 1.83, 1.13, 5.80, 2.04]]
print map(mean, zip(*a))
I used the fastgreedy algorithm in igraph for my community detection in a weighted, undirected graph. Afterwards I wanted to have a look at the modularity and I got different values for different methods and I am wondering why. I included a short example, which demonstrates my problem:
library(igraph)
d<-matrix(c(1, 0.2, 0.3, 0.9, 0.9,
0.2, 1, 0.6, 0.4, 0.5,
0.3, 0.6, 1, 0.1, 0.8,
0.9, 0.4, 0.1, 1, 0.5,
0.9, 0.5, 0.8, 0.5, 1), byrow=T, nrow=5)
g<-graph.adjacency(d, weighted=T, mode="lower",diag=FALSE, add.colnames=NA)
fc<-fastgreedy.community(g)
fc$modularity[3]
#[1] -0.05011095
modularity(g,membership=cutat(fc,steps=2),weights=get.adjacency(g,attr="weight"))
#[1] 0.07193047
I would expect both of the values to be identical and if I try the same with an unweighted graph, I get the same values.
d2<-round(d,digits=0)
g2<- graph.adjacency(d2, weighted=NULL, mode="lower",diag=FALSE, add.colnames=NA)
fc2<-fastgreedy.community(g2)
plot(fc2,g2)
fc2$modularity[3]
#[1] 0.15625
modularity(g2,membership=cutat(fc2,steps=2))
#[1] 0.15625
Another user had a similar problem, but I have the current version of igraph, so that should not be the problem. Can someone explain to me why there is a difference or is there a problem with my code I don't see?
The line
modularity(g,membership=cutat(fc,steps=2),weights=get.adjacency(g,attr="weight"))
is wrong. If you want to pass the weights of edges to modularity(), do it with E(g)$weight:
modularity(g, membership = cutat(fc, steps = 2), weights = E(g)$weight)
# [1] -0.05011095
I am using Octave.
My problem is this: I want to fill the bubbles of my scatter plot, as well as place a legend. But I get errors when I try to use 'filled', and no legend comes up when I use legend(...).
Part of my code looks like this:
%ALL SAMPLES, PHI(Signal) # THETA(Sample)=0
figure(5)
plot( Angles(:,1)([18:27]), ALL([18:27]), 10, [1 0 1]); %Magenta
hold on
scatter(Angles(:,1)([68:76]), ALL([68:76]), 10, [0 0 0]); %Black
scatter(Angles(:,1)([86:95]), ALL([86:95]), 10, [1 0 0]); %Red
scatter(Angles(:,1)([119:127]), ALL([119:127]), 10, [0 1 0]); %Green
scatter(Angles(:,1)([133:141]), ALL([133:141]), 10, [0 0 1]); %Blue
hold off
xlabel('Signal PMT angle (Sample angle at 0)');
ylabel('Normalized (signal/monitor) intensity');
legend('Control', 'Control', '1+2','Virgin','Cycle #1', 'Location','NorthEast');
title('Plot of All Samples, "-int Intensity"')
I know it should beplot( Angles(:,1)([18:27]), ALL([18:27]), 10, [1 0 1], 'filled');, but I receive errors when I do that. Also, a legend never seems to show up.
Apparently there is a problem with using legend with scatter in Octave. Based on this post:
http://octave.1599824.n4.nabble.com/Legend-in-scatter-plot-td3568032.html
the trick is to use the plot function to make scatter plot. I wrote the following function for plotting a bunch of scatter plots on the same axis.
This function takes in a bunch of cell arrays of the same length. Each element of the cell array corresponds to a separate series. The function returns a cell array of the same length containing the handle associated with each plot. The arguments of the function are explained below:
x_vals: a cell array of arrays of doubles corresponding to x values.
y_vals: a cell array of arrays of doubles corresponding to y values.
sizes: a cell array of doubles representing the size of the markers.
colors: a cell array of double arrays of length 3, representing [R, G, B] color values of the markers.
styles: a cell array of strings representing the shape of the markers.
function [handles] = scatter_series_set(x_vals, y_vals, sizes, colors, styles)
N = length(x_vals);
if ( (~ ( N == length(y_vals))) || (~ ( N == length(sizes))) || ...
(~ ( N == length(colors))) || (~ ( N == length(styles))) )
error('scatter_series_set: all arguments must be cell arrays of the same length');
end
%plot the first series
handles = cell([N, 1]);
handles{1} = plot(x_vals{1}, y_vals{1});
set(handles{1}, 'linestyle', 'none');
set(handles{1}, 'marker', styles{1});
set(handles{1}, 'markersize', sizes{1});
set(handles{1}, 'color', colors{1});
%plot additional series if present
if N > 1
hold on;
for ind = 2:N
handles{ind} = plot(x_vals{ind}, y_vals{ind});
set(handles{ind}, 'linestyle', 'none');
set(handles{ind}, 'marker', styles{ind});
set(handles{ind}, 'markersize', sizes{ind});
set(handles{ind}, 'color', colors{ind});
end
hold off;
end
end
The following example demonstrates how to use this function.
x1 = 0:(2*pi/100):(2*pi);
x2 = 2*x1;
y1 = sin(x1);
y2 = cos(x1);
y3 = sin(x2);
y4 = cos(x2);
names = {'a', 'b', 'c', 'd'};
x_vals = {x1, x1, x1, x1};
y_vals = {y1, y2, y3, y4};
sizes = {10, 10, 10, 10};
colors = {[1, 0, 0], [0, 0, 1], [0, 0, 0], [0.7071, 0, 0.7071]};
styles = {'^', 's', 'x', '+'}
scatter_series_set(x_vals, y_vals, sizes, colors, styles);
legend(names, 'location', 'southeast');
The example code produces the following plot:
The following works for me:
n = 100;
x = randn(n, 1);
y = randn(n, 1);
S = rand(n, 1)*20;
hold on
scatter(x(1:50), y(1:50), S(1:50), "red", "filled")
scatter(x(51:100), y(51:100), S(51:100), "green", "filled")
hold off
print('-depsc', 'bubbleplot.eps');
However, I'm not able to add a legend, and I didn't find any bug report or indication of a missing functionality for this. So, as an alternative, I would suggest adding marker and text to your plot.