problem saving pdf file in R with ggplot2 - macos

I am encountering an odd problem. I am able to create and save pdf file using R/ggplot2 and view them while the R Console is running. As soon as I exit the R console, Preview on Mac OS X will no longer display the PDF. I have been able to save .png files w/o problem, but for reasons beyond my control, I need to save in pdf files. The code I am using to save is as follows:
pdfFile <-c("/Users/adam/mock/dir/structure.pdf")
pdf(pdfFile)
ggplot(y=count,data=allCombined, aes(x=sequenceName, fill=factor(subClass))) + geom_bar()
ggsave(pdfFile)
Has anyone encountered a similar problem? If so, what do I need to do to fix it?
Thank you very much for your time.

The problem is that you don't close the pdf() device with dev.off()
dat <- data.frame(A = 1:10, B = runif(10))
require(ggplot2)
pdf("ggplot1.pdf")
ggplot(dat, aes(x = A, y = B)) + geom_point()
dev.off()
That works, as does:
ggplot(dat, aes(x = A, y = B)) + geom_point()
ggsave("ggplot1.pdf")
But don't mix the two.

It is in the R FAQ, you need a print() around your call to ggplot() -- and you need to close the plotting device with dev.off() as well, ie try
pdfFile <-c("/Users/adam/mock/dir/structure.pdf")
pdf(pdfFile)
ggplot(y=count,data=allCombined,aes(x=sequenceName,fill=factor(subClass)))
+ geom_bar()
dev.off()
Edit: I was half-right on the dev.off(), apparently the print() isn;t needed. Gavin's answer has more.

The following plot
pdf("test.pdf")
p <- qplot(hp, mpg, data=mtcars, color=am,
xlab="Horsepower", ylab="Miles per Gallon", geom="point")
p
dev.off()
works in the console but not in a function or when you source this from a file.
myfunc <- function() {
p <- qplot(hp, mpg, data=mtcars, color=am,
xlab="Horsepower", ylab="Miles per Gallon", geom="point")
p
}
pdf("test.pdf")
myfunc()
dev.off()
Will produce a corrupt pdf file and the way to fix it us use
print(p)
within a function.
In a console. "p" is automatically printed but not in a function or when you source the file.

You can also change the filename of your pdf plot within ggsave if you want to call it something other than "ggplot1" or whatever concise object name you chose; just give the filename first and then tell it which plot you're referring to, for example:
a <- ggplot(dat, aes(x = A, y = B)) + geom_point()
ggsave("Structure.pdf",plot=a)

Related

Octave: How do I examine variables created in a seperate .m file?

I have 2 .m files, for an example say "project_main.m" and "my_function.m"
When I run the program in Octave it works fine. However the only variables I can see in the workspace area are those created in project_main.m, I would like to examine variables created in my_function.m from the workspace area.
Example:
project_main.m:
close all;
clear all;
clc;
X = 1;
Y = 2;
%---call function in external .m file---
my_function(X, Y);
my_function.m:
function functionResults = my_function(iX, iY)
fprintf("X = %d, Y = %d\n", iX, iY);
Z = iX*iY;
fprintf("Z = %d\n", Z);
end
This will give me on the command window:
X = 1, Y = 2
Z = 2
>>
As expected. However in the workspace area I only see X and Y, not Z:
I know I can see Z on the command window, but how do I examine variables created in separate .m files from the workspace area?
You'll need a debugger. This documentation page seems like a good start. Either run your function line-by-line using the command window, or set breakpoints to return the current function workspace to the global one.
Basically: variables within functions are private to that function and only the ones you output are copied into your workspace. In your case that is nothing, since fprintf doesn't return the output, it merely prints to the command window.

Writing Macro in ImageJ to open, change color, adjust brightness and resave microscope images

I'm trying to write a code in Image J that will:
Open all images in separate windows that contains "488" within a folder
Use look up tables to convert images to green and RGB color From ImageJ, the commands are: run("Green"); and run("RGB Color");
Adjust the brightness and contrast with defined values for Min and Max (same values for each image).
I know that the code for that is:
//run("Brightness/Contrast..."); setMinAndMax(value min, value max); run("Apply LUT");
Save each image in the same, original folder , in Tiff and with the same name but finishing with "processed".
I have no experience with Java and am very bad with coding. I tried to piece something together using code I found on stackoverflow and on the ImageJ website, but kept getting error codes. Any help is much appreciated!
I don't know if you still need it, but here is an example.
output_dir = "C:/Users/test/"
input_dir = "C:/Users/test/"
list = getFileList(input_dir);
listlength = list.length;
setBatchMode(true);
for (z = 0; z < listlength; z++){
if(endsWith(list[z], 'tif')==true ){
if(list[z].contains("488")){
title = list[z];
end = lengthOf(title)-4;
out_path = output_dir + substring(title,0,end) + "_processed.tif";
open(input_dir + title);
//add all the functions you want
run("Brightness/Contrast...");
setMinAndMax(1, 15);
run("Apply LUT");
saveAs("tif", "" + out_path + "");
close();
};
run("Close All");
}
}
setBatchMode(false);
I think it contains all the things you need. It opens all the images (in specific folder) that ends with tif and contains 488. I didn't completely understand what you want to do with each photo, so I just added your functions. But you probably won't have problems with adding more/different since you can get them with macro recorder.
And the code is written to open tif files. If you have tiff just be cerful that you change that and also change -4 to -5.

Using rgl package to plot a 2D image from local disk

This is probably pretty straightforward but I'm stuck for hours...
I don't a code example but I'll keep it simple.
My app looks into a folder and checks if STL files exist based on a selectizeinput.
Then, it plots the STL without an issue.
However, the amount of STL in the folder is scarce compared to the selectize options.
My goal is to have an if statement that outputs the STL if there an STL file (so far, so good...) and outputs a 2D image (something like 404 file not found).
I looked at rgl documentation and this last part (2D image) is where I can't seem to figure out how to plot it...
Hopefully I was clear and someone can point me in the right direction.
Thanks in advance.
EDIT:
Here is an example of code to clarify
observe({
req(input$slider1)
# Load filenames in STL folder
stl_files <- list.files("~www/STL/", pattern = ".stl", full.names = F)
if (is.null(input$slider1) || length(input$slider1) < 1 || input$slider1 == F || input$slider1 == "$0" || (paste0(input$slider1[1],".stl") %in% stl_files) == F ){
output$"3D-plot_1" <- renderRglwidget({
# here I would like to plot a 2D image in case the stl file does not exit and this where I'm stuck.
})
} else {
# Create STL Plot
output$"3D-plot_1" <- renderRglwidget({
stl_1 <- readSTL(con = paste0("~www/STL/", input$slider1, ".stl"), ascii = F, plot = F)
stl_centered_1 <- scale(stl_1, center = T, scale = F)
options(rgl.useNULL=TRUE)
open3d()
rgl::triangles3d(stl_centered_1, aspect = "iso", col = "grey")
bg3d("black")
scene1 <- scene3d()
rglwidget(scene1)
})
}
})

Trying to update graph using CSV

I have a question. I am trying to plot a live graph while continuously updating a CSV file continuously from a LIDAR sensor. However when I call animation.FuncAnimation(... the graph does not continuously update. If I rerun, I see the graph updated. When I view the CSV file, I see has been updating.
class SecondGraph:
def animate(i):
graph_data = open(NameofCSV,'r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 0:
x, y = line.split(' ')
xs.append(float(x))
ys.append(float(y))
ax1.clear()
ax1.plot(ys, xs)
ani = animation.FuncAnimation(fig, SecondGraph.animate, interval=10)
When someone has a chance, can someone guide me in the right direction here. I do not think I need to plot my full code, but if you need to see it. Let me know.
Disregard. I think I know the answer. The CSV does not update automatically, which may be the problem. I do not think there is anything wrong with my code that I posted.

Making a gif from images

I have a load of data in 100 .sdf files (labelled 0000.sdf to 0099.sdf), each of which contain a still image, and I'm trying to produce a .gif from these images.
The code I use to plot the figure are (in the same directory as the sdf files):
q = GetDataSDF('0000.sdf');
imagesc(q.data');
I've attempted to write a for loop that would plot the figure and then save it with the same filename as the sdf file but to no avail, using:
for a = 1:100
q=GetDataSDF('0000.sdf');
fh = imagesc(q.dist_fn.x_px.Left.data');
frm = getframe( fh );
% save as png image
saveas(fh, 'current_frame_%02d.jpg');
end
EDIT: I received the following errors when trying to run this code:
Error using hg.image/get
The name 'Units' is not an accessible property for an instance of class 'image'.
Error in getframe>Local_getRectanglesOfInterest (line 138)
if ~strcmpi(get(h, 'Units'), 'Pixels')
Error in getframe (line 56)
[offsetRect, absoluteRect, figPos, figOuterPos] = ...
Error in loop_code (line 4)
frm = getframe( fh );
How do I save these files using a for loop, and how do I then use those files to produce a movie?
The reason for the error is that you pass an image handle to getframe, but this function excpects a figure handle.
Another problem is that you always load the same file, and that you saveas will not work for gifs. (For saving figures as static images, maybe print is the better option?)
I tried to modify my own gif-writing loop so that it works with your data. I'll try to be extra explicit in the comments, since you seem to be starting out. Remember, you can always use help name_of_command to display a short Matlab help.
% Define a variable that holds the frames per second your "movie" should have
gif_fps = 24;
% Define string variable that holds the filename of your movie
video_filename = 'video.gif';
% Create figure 1, store the handle in a variable, you'll need it later
fh = figure(1);
for a = 0:99
% Prepare file name so that you loop over the data
q = GetDataSDF(['00' num2str(a,'%02d') 'sdf']);
% Plot image
imagesc(q.dist_fn.x_px.Left.data');
% Force Matlab to actually do the plot (it sometimes gets lazy in loops)
drawnow;
% Take a "screenshot" of the figure fh
frame = getframe(fh);
% Turn screenshot into image
im = frame2im(frame);
% Turn image into indexed image (the gif format needs this)
[imind,cm] = rgb2ind(im,256);
% If first loop iteration: Create the file, else append to it
if a == 0;
imwrite(imind,cm,video_filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,video_filename,'gif','WriteMode','append','DelayTime',1/gif_fps);
end
end
One more note: When the size of the data is the same for each plot, it makes sense to only use the plot(or in this case, imagesc) command once, and in later loop iterations replace it with a set(ah,'Ydata',new_y_data) (or in this case set(ah,'CData',q.dist_fn.x_px.Left.data'), where ah is a handle of the plot axes (not the plot figure!). This is orders of magnitude faster than creating a whole new plot in each loop iteration. The downside is that the scaling (here, the color-scaling) will be the same for each plot. But in every case that I have worked on so far, that was actually desirable.

Resources