I have several questions to do with handling some data in R:
I am using this statement: detailsTable <- read.table(file=commandArgs()[6], header=TRUE, col.names=c("a", "b", "c", "d", "e")) and it seems that the table is not being loaded correctly... but if I specify the path of the file I am loading excplicitly then all goes well. What am I doing wrong?
I plot the data contained in that table mentioned above. How do I save the plot (eg: plot.savePDF("plot.pdf")) to a PDF file?
How could I redirect the output of, for example, cor(detailsTable$a, detailsTable$b) to a file? and how do I write a simple string to a file. eg: "Correlation of the data: " + cor(...)
How do I plot the line of best fit on an existing plot?
All of this is in R.
Many thanks to anyone who can help,
ExtremeCoder
I plot the data contained in that table mentioned above. How do I save the plot (eg: plot.savePDF("plot.pdf")) to a PDF file?
pdf("filename.pdf")
plot(...)
dev.off()
How could I redirect the output of, for example, cor(detailsTable$a, detailsTable$b) to a file? and how do I write a simple string to a file. eg: "Correlation of the data: " + cor(...)
check the write.table manual page (?write.table)
How do I plot the line of best fit on an existing plot?
x <- 1:10
y <- 2 * x + runif(10)
plot (x, y, pch=20)
fit <- glm(y~x)
coefs <- coef(fit)
abline(coefs, lwd=2, col='red')
# Or also, without finding the coefficients
abline(fit, lwd=2, col='red')
You can redirect output using sink().
How to save the plot you're producing depends on which plotting system you're using. Assuming it's base graphics, you need to start a pdf graphics device, then plot to it.
pdf(file = "path/file.pdf", width = 5, height = 5)
...
#plotting commands here
...
dev.off()
Related
I plotted a scatterplot with seaborn library and I want to change the legend text but dont know how to do that.
example:
The following is iris dataset with species columns encoded in 0/1/2 as per species.
plt.figure(figsize=(8,8))
pl = sns.scatterplot(x='petal_length', y ='petal_width', hue='Species', data=data, s=40,
palette='Set1', legend='full')
I want to change the legends text from [0, 1, 2] to ['setosa', 'versicolor', 'virginica'].
can anybody help.
First, Seaborn (and Matplotlib) usually picks up the labels to put into the legend for hue from the unique values of the array you provide as hue. So as a first step, check that the column Species in your dataframe actually contains the values "setosa", "versicolor", "virginica". If not, one solution is to temporarily map them to other values, for the purpose of plotting:
legend_map = {0: 'setosa',
1: 'versicolor',
2: 'virginica'}
plt.figure(figsize=(8,8))
ax = sns.scatterplot(x=data['petal_length'], y =data['petal_width'], hue=data['species'].map(legend_map),
s=40, palette='Set1', legend='full')
plt.show()
Alternatively, if you want to directly manipulate the plot information and not the underlying data, you can do by accessing the legend names directly:
plt.figure(figsize=(8,8))
ax = sns.scatterplot(x='petal_length', y ='petal_width', hue='species', data=data, s=40,
palette='Set1', legend='full')
l = ax.legend()
l.get_texts()[0].set_text('Species') # You can also change the legend title
l.get_texts()[1].set_text('Setosa')
l.get_texts()[2].set_text('Versicolor')
l.get_texts()[3].set_text('Virginica')
plt.show()
This methodology allows you to also change the legend title, if need be.
I have with 5 different values and I would like to create a legend ?
These are continuous data, I need small coloured squares !
How to add legend in imagesc plot in matlab Something like this but with squares, I tried replacing "line" by "rectangle" but that's not the trick apparently !
Thank you
I just used your linked example code and modified it a little:
N=4; % # of data types, hence legend entries
Data = randi(N,30,30); % generate fake data
imagesc(Data) % image it
cmap = jet(N); % assigen colormap
colormap(cmap)
hold on
markerColor = mat2cell(cmap,ones(1,N),3);
L = plot(ones(N), 'LineStyle','none','marker','s','visible','off');
set(L,{'MarkerFaceColor'},markerColor,{'MarkerEdgeColor'},markerColor);
legend('A','B','C','D')
The trick is to use markers instead of the line itself.
it returns:
I tried the following program for reading multiple images(about 300 images). Now I want to store these images immediately after reading each to some location by some name as g1,g2,g3... Is it possible to do this in a loop?
Here is my attempt:
for i=1:5
m=imread(['C:\Users\shree\Desktop\1\im' num2str(i) '.jpg']);
figure,imshow(m);
end
I highly recommend that you store them in a cell array:
for k=1:5
image_path = ['C:\Users\shree\Desktop\1\im' num2str(i) '.jpg']; %// I have moved this to be on its own line as it will make debugging easier. You don't have to, but I think it's a good idea.
images_all{k} = imread(image_path);
end
By using eval to create variable names like g1, g2 etc you pollute your workspace with an unmanageable amount of variables. Plus if they are all in a cell array then it's really easy to apply the same function to each of them either in a loop or with cellfun.
For example if you want to convert them all to greyscale now:
images_grey = cellfun(#rgb2gray, images_all, 'UniformOutput', false);
You can simply save all them into one big matrix:
for i=1:5
images_all(:, :, :, i) = imread(['C:\Users\shree\Desktop\1\im' num2str(i) '.jpg'])
end
After this, all images will be stored in images_all (here assume that all images are colored images, i.e. 3 channels).
Try this -
for i=1:5
img =imread(['C:\Users\shree\Desktop\1\im' num2str(i) '.jpg']);
evalc(['g' num2str(i) '=img;']);
end
figure,imshow(g1);
figure,imshow(g2);
Another approach could be to use STRUCT and store those images as fields of a struct.
Storing as a 4D matrix is another efficient way as suggested by herohuyongtao.
I am trying to overlay an activation map over a baseline vasculature image but I keep getting the same error below:
X and Y must have the same size and class or Y must be a scalar double.
I resized each to 400x400 so I thought it would work but no dice. Is there something I am missing? It is fairly straight forward for a GUI I am working on. Any help would be appreciated.
a=imread ('Vasculature.tif');
b = imresize (a, [400,400]);
c=imread ('activation.tif');
d= imresize (c, [400,400]);
e=imadd (b,d);
Could it be the bit depth or dpi?
I think one of your images is RGB (size(...,3)==3) and the other is grayscale (size(...,3)==1). Say the vasculature image a is grayscale and the activation image c is RGB. To convert a to RGB to match c, use ind2rgb, then add.
aRGB = ind2rgb(a,gray(256)); % assuming uint8
Alternatively, you could do aRGB = repmat(a,[1 1 3]);.
Or to put the activation image into grayscale:
cGray = rgb2gray(c);
Also, according to the documentation for imadd the two images must be:
nonsparse numeric arrays with the same size and class
To get the uint8 and uint16 images to match use the im2uint8 or im2uint16 functions to convert. Alternatively, just rescale and cast (e.g. b_uint8 = uint8(double(b)*255/65535);).
Note that in some versions of MATLAB there is a bug with displaying 16-bit images. The fix depends on whether the image is RGB or gray scale, and the platform (Windows vs. Linux). If you run into problems displaying 16-bit images, use imshow, which has the fix, or use the following code for integer data type images following image or imagesc:
function fixint16disp(img)
if any(strcmp(class(img),{'int16','uint16'}))
if size(img,3)==1,
colormap(gray(65535)); end
if ispc,
set(gcf,'Renderer','zbuffer'); end
end
chappjc's answers is just fine, I want to add a more general answer to the question how to solve the error message
X and Y must have the same size and class or Y must be a scalar double
General solving strategy
At which line does the error occur
Try to understand the error message
a. "... must have the same size ...":
Check the sizes of the input.
Try to understand the meaning of your code for the given (type of) input parameters. Is the error message reasonable?
What do you want to achieve?
Useful command: size A: returns the size of A
b. "... must have the same class ...":
Check the data types of the input arguments.
Which common data type is reasonable?
Convert it to the chosen data type.
Usefull command: whos A: returns all the meta information of A, i.e. size, data type, ...
Implement the solution: your favorite search engine and the matlab documentation are your best friend.
Be happy: you solved your problem and learned something new.
A simple code :
a=imread ('image1.jpg');
b=imresize (a, [400,400]);
subplot(3,1,1), imshow(b), title('image 1');
c=imread ('image2.jpg');
d= imresize (c, [400,400]);
subplot(3,1,2), imshow(d), title('image 2');
[x1, y1] = size(b) %height and wedth of 1st image
[x2, y2] = size(d) %height and wedth of 2nd image
for i = 1: x1
for j = 1: y1
im3(i, j)= b(i, j)+d(i, j);
end
end
subplot(3,1,3), imshow (im3), title('Resultant Image');
I am getting more than ...slightly flustered... at trying to do what should otherwise be a very, very simple task.
I want to use a particular figure, say, figure(3), for doing imagesc. So in the beginning of my code, I always do this:
f3 = figure(3);
a3 = gca;
Then, I get some matrix data, of arbitrary size. Say that I got data of size 231 x 322. Now, I want to tell MATLAB, to perform imagesc(data), but on figure(3).
How do I do that?? imagesc doesnt take figure or axes handles, and this is becoming very, very frustrating... thanks!
imagesc takes a 'parent' parameter. This is indirectly documented via the image function.
For example:
imdata = imread('ngc6543a.jpg');
f = figure;
a1 = subplot(211);
a2 = subplot(212);
image(imdata,'parent',a1);
imagesc(imdata,'parent',a2);