Showing posts with label vector graphics. Show all posts
Showing posts with label vector graphics. Show all posts
Tuesday, February 13, 2018
Haplotype pie charts: automated pie colors!
Recently I have been polishing up some genetics work and I was frustrated at the prospect of having to re-color the haplotype network figures by hand at least once more. This drove me to see if I could finally get the R package 'igraph' working. Sure enough, I was able to get it to work! Here is the link to the updated original post with code and instructions.
Monday, August 17, 2015
Update to viewing and printing postscript files
A Windows 8.1 update to 'The Mysteries of Postscript'
Installing GSView and Ghostscript seems to work fine on Windows 8.1. I haven't tested out the Inkscape connection because I never end up using it, as it seemed pretty inconsistent. After installing Ghostscript and GSView with no problems, I set up the .eps printer as described in this tutorial. However, at least with the driver I chose (first HP one in the list which was HP Color LaserJet 2500 PS Class Driver), there were NOT any PostScript Options under Document Options in the configuration step. So I tried to go ahead and print my .eps file, and at least with the pdf I used, it worked fine. I'm not sure if that has to do with Windows 8.1, or if I just happened to select a handy driver.
Monday, January 19, 2015
The mysteries of postscript files
Last week I talked about saving figures from R. I mentioned .eps files, a type of vector image that is sometimes requested as a format for figures in submitting manuscripts for publication. Even without having ghostscript installed on a Windows machine, R will correctly save the image (at least it did on mine). However, you can't view it. Additionally, if you make an svg file and try to save it as a .eps file from Inkscape, it doesn't save the file correctly. (My test file left off the axis labels, for example.) So, here's how to view, and save (or print to) .eps files on a Windows 7 computer (I assume similar steps will work for other Windows computers).
If you need to add anything to your R plot, then you have two options.
(1) If you have Adobe Illustrator, save it as .eps, then open in Illustrator and edit it to your liking.
(2) Don't have Illustrator (like me)? Save as a .svg from R, edit in Inkscape, then save as .eps (sometimes this works, sometimes it cuts off pieces of the figure and I haven't figured out why). If the .eps from Inkscape is not good, save your .svg file instead as a .pdf. Then open the .pdf in Adobe Acrobat Pro (just the reader won't work) and save as .eps. Or, if you don't have Adobe Acrobat Pro, print as .eps from your pdf reader. A few more steps, but still doable with all free programs (Ghostscript, GSView, Inkscape, and your pdf reader of choice) and pretty easy.
Viewing .eps files (works well, do this!)
First, I downloaded GPL Ghostscript. Choose the appropriate type (32-bit or 64-bit). You can find out which you have by right-clicking on "Computer" in the start menu and selecting "Properties". This detail is under the "System" section as "System type". I installed the program and then got GSView and installed it. I tried opening a .eps file. It worked!Inkscape and .eps files (sometimes it works, sometimes it doesn't, so skip this step if you want)
Now, Inkscape. I've always had mixed success saving files from there to .eps files. Theoretically, this should work. Sometimes it cuts off bits of the graph though. If you want to try it, here's an example. Just be warned I've never gotten it to completely work! Open a .svg file in Inkscape (perhaps the one created last week). I saved again, and it still cuts off the axis labels and axis numbering. I need to link up the two programs according to the Inkscape forum. In the Start Menu, click on "Computer". In that window near the "System Properties". Go to the "Advanced" tab and click on the "Environment Variables" button. There are two lists of variables. The top one is "User variables for [yourusername]". Click "New" and name the new variable "GS_PROG" with value: "C:\Program Files\gs\gs9.15\bin\gswin32.exe"; navigate there to confirm it's where your file lives (or gswin64.exe if you have 64-bit windows). Under "System variables" edit "PATH". There are already a bunch of path values listed in there; DO NOT DELETE THEM. At the end of the current list, place a semicolon, and add: "C:\Program Files\gs\gs9.15\bin;C:\Program Files\gs\gs9.15\lib", similar to how it's described in this tutorial. Then click "OK" on both windows. Now, start Inkscape. It now recognizes .eps files as a type it can import. However, I've never been able to get that to work (Inkscape just locks up). So, close the import window and just open one of your .svg files. You can then save it as a .pdf, open the .pdf in your usual pdf viewer, and then print it to a .eps file in the next section.Printing as .eps (works well!)
You can print to .eps files using the regular print features in whatever program. I followed these instructions (where to find "Add Printer" varies a bit depending on which version of Windows you have but it's pretty easy to find. If you are having trouble just type "Add Printer" into the Start Menu search box. Anyway, it worked beautifully. I used an existing port ("FILE: print to file") as they said to. With this .eps printer set up, I could take my .svg to .pdf in Inkscape, then print to .eps from the pdf viewer (I use Foxit Reader but this print to .eps should work in any program that prints). I can't recall if you have to already have Ghostscript installed to make this work, but you'll need to view it to confirm, so you might as well get Ghostscript and GSView installed.Summary of how I get to .eps files
Do you need to add anything to your file after using R to create your figure? No? Then use R and view them in GSView. Easy!If you need to add anything to your R plot, then you have two options.
(1) If you have Adobe Illustrator, save it as .eps, then open in Illustrator and edit it to your liking.
(2) Don't have Illustrator (like me)? Save as a .svg from R, edit in Inkscape, then save as .eps (sometimes this works, sometimes it cuts off pieces of the figure and I haven't figured out why). If the .eps from Inkscape is not good, save your .svg file instead as a .pdf. Then open the .pdf in Adobe Acrobat Pro (just the reader won't work) and save as .eps. Or, if you don't have Adobe Acrobat Pro, print as .eps from your pdf reader. A few more steps, but still doable with all free programs (Ghostscript, GSView, Inkscape, and your pdf reader of choice) and pretty easy.
Saturday, February 22, 2014
Workflow going from Geneious to R to Inkscape for a haplotype network
I wanted to make a network of mtDNA haplotypes showing the number of mutation steps between haplotypes and showing sites or other attributes as pie charts at each node.
To get the haplotypes, I aligned my sequences in Geneious. Presumably you could do this in whatever your program of choice is. I made sure my sequences had appropriate sample numbers (to merge with attributes later in R). I trimmed the sequences so they matched in length. End gaps could be counted as the same length, but then you'll get lots of haplotypes that are simply different lengths of gaps at the end. I exported the data from Geneious as a .fasta file.
Now you have a .fasta file of sequences that are all the same length. I used code from this blog post to create the haplotype network. It worked great using functions in the R package pegas. The code there uses site to make up the slices of the pie, but you can also use other attributes (I used phenotype and transect) of the sampled individuals.
The haplotype network produced from step 2 has a rainbow color palette, which is pretty, but it may not fit with your desired color schemes or with black-and-white printing in a publication. Some of the colors can be hard to tell apart too. In my case, it was hard to interpret because I needed light and dark versions of two sets of birds within the haplotypes. I was having trouble with the igraph package that was suggested to edit colors, so eventually I decided to just export the figure as a scalable vector graphic (.svg).
I then edited the .svg file's colors in Inkscape, a free, open-source vector graphics editor. Once you open your figure in Inkscape, click on the figure. That selects it. Then you can right-click and find "ungroup" in the menu or go to the Object menu for "ungroup". Usually then you can select individual pieces of the figure, but if not, keep ungrouping pieces of the figure until you can.
Now, you should be able to grab pieces of the pie and change their color. You can do more than one by holding down the shift key while selecting additional pie slices and the legend (to make sure the legend color matches your pie slice color). Just double-click on the color you want in the bar on the bottom part of the screen. Repeat as needed for the other pie slices.
One problem I ran into was distinguishing a few of the colors on the original figure. You can use the ink dropper tool (press F7 or find it in the toolbar on the left side of the screen) to make sure you are correctly identifying particular colors as the same ones and not accidentally merging different sites or attributes in your final figure. By holding the ink dropper tool over a color, you show the color's hexadecimal code in a gray area below the color palette bar on the bottom of the screen.
From within Inkscape, you can then use "save as" to get your image in another vector graphic format (.ps or .eps) for publication, or use "export bitmap" (also in the File menu) to create a new raster graphic .png for publication or presentation.
I have figured out how to use the R package igraph to automate the coloring of the pie slices.
Unfortunately I haven't figured out how to put the tick marks back on for number of changes between haplotypes, but the line lengths are still proportional to number of changes. (If anyone knows how to do that, please let me know.)
Below is a complete example that will take you from creating the network to the final plot.
library(pegas)
library(igraph)
library(plyr)
library(reshape)
########################
#Step 1a. Load your alignment and use haploNet() to create the haplotype network.
#Load the pegas package sample data "woodmouse".
#This step is adapted from pegas help.
data(woodmouse)
set.seed(42)
x <- woodmouse[sample(15, size = 30, replace = TRUE), ]
h <- haplotype(x)
(net <- haploNet(h))
plot(net)
########################
#Step 1b. Have sites.
#I'm going to add in some arbitrary sample attributes that we'll use for pie chart testing.
#For your actual dataset, you would load a dataframe of localities for each sample.
#The samples and their sites should be in the same order as the samples in the file you used for haplotypes in 1a.
#Here, we randomly generate assignments to sites A, B, and C for the woodmouse dataset, which now has 30 samples.
sitenames <- c("A", "B", "C")
set.seed(84)
sites <- data.frame("site" = sample(sitenames,
size = 30,
replace = TRUE))
########################
#Step 2. Assign haplotypes to your site dataframe.
#This code is adapted from a blog post by Jimmy O'Donnell (jodonnellbio at gmail) with help from Kim Tenggardjaja.
#Original posting: http://jimmyodonnell.wordpress.com/2013/11/23/haplotype-networks-in-r-updated/
#Adaptations to this code by Claire Curry (curryclairem@gmail.com)
#Now, fill in the haplotypes for each site.
#You will have to do this with your real dataset.
#The site and haplotype dataframes must be in the SAME SAMPLE ORDER.
#Add empty column to sites dataframe for haplotypes
sites<-cbind(sites,
haplotype=rep(NA,
nrow(sites)))
#Assign haplotypes to the samples automatically using a loop
for (i in 1:length(labels(h))){
sites$haplotype[attr(h,
"index")[[i]]]<-i
}
########################
#Step 3. Convert to igraph format from haplonet.
#Here's my new adaptation to plot colors automatically in igraph, as suggested on the original blog post.
#Get igraph network
net.igraph <- as.igraph(net,
directed = FALSE, #Leave network arrows off as they are not relevant to our case.
use.labels = TRUE,
altlinks = FALSE) #only get main links between haplotypes or you'll end up with tons of extra lines
#Get the haplotype numbers in their weird order so you can order colors and sizes correctly.
newnums <- as.roman(as.character(V(net.igraph)$name))
V(net.igraph)$name <- newnums
########################
#Step 4.Count up haplotype frequencies and site frequencies.
#This code is adapted from a blog post by Jimmy O'Donnell (jodonnellbio at gmail) with help from Kim Tenggardjaja.
#Original posting: http://jimmyodonnell.wordpress.com/2013/11/23/haplotype-networks-in-r-updated/
#Adaptations to this code by Claire Curry (curryclairem@gmail.com)
#Count how many individuals for each haplotype
count.hap0<-ddply(sites,
.(haplotype),
summarise,
freq=length(haplotype))
#Be sure to add in our new ordering!
count.hap <- count.hap0[order(match(rownames(count.hap0),
newnums)),"freq"]
#for each plot, build frequency matrix that tells how to fill the pies by site frequency.
dfcount_site<-ddply(sites,
.(site, haplotype),
summarise,
freq=length(site))
dc.site00 <- cast(haplotype ~ site,
data = dfcount_site,
value = "freq",
fill = 0)
dc.site0 <-dc.site00
########################
#Step 5. Convert the site frequencies into the correct list format and the correct order to match the igraph object.
#Now, onto more igraph adaptations.
dc.site0$haplotype<-NULL #Remove the haplotype row before turning this into a matrix.
#Turn the haplotype frequencies into a matrix in the NEW IGRAPH ORDER.
dc.site1<-t(as.matrix(dc.site0[order(match(rownames(dc.site0),
newnums)),]))
#You must do this step to match the ordering of the cast dataframe haplotypes to the ordering used in igraph,
#otherwise the colors and sizes will be off.
#Then split the matrix out into a list.
dc.site <- split(dc.site1,
rep(1:ncol(dc.site1),
each = nrow(dc.site1)))
#Remember, if you go back to your haplotype counts to check that colors and sizes are correct,
#that we rearranged dc.site to be in the order that the haplotypes are stored
#You can check V(net.igraph)$name to see them again.
#dc.site0's haplotype column shows the haplotype numbers, but doing order(match() then puts dc.site1 and dc.site into
#the order the haplotypes are stored in the igraph network.
#Hence, we use the following step to make it more obvious by naming each list element with the haplotype number.
names(dc.site) <- V(net.igraph)$name
########################
#Step 6. Plot the network.
plot(net.igraph, #the igraph object is always a list of 10 so far as I can tell, regardless of how many haplotypes you used.
vertex.shape="pie",
vertex.pie = dc.site,
#vertex.pie specifies where you are getting the pie slice counts.
vertex.pie.color=list(c("black",
"orange",
"blue")),
#The colors are the number of categories you have, must be in a list, in the same order as your sites.
vertex.size = 5*(count.hap),
#number of samples for each haplotype, multiplied to make bigger if desired.
#vertex.label = NA)#, #for no vertex labels (ie no hapotype numbers added)
#vertex.label.cex = 1)#, #if you want bigger haplotype numbers.
vertex.label.dist = 2.5) #how far from pie you want the haplotype numbers)
#Add a legend.
legend(x= "bottomleft",
bty="n",
pt.bg=c("black",
"orange",
"blue"),
col="black",
pch=22,
legend=c("Site A",
"Site B",
"Site C"))
1. Creating the haplotypes
To get the haplotypes, I aligned my sequences in Geneious. Presumably you could do this in whatever your program of choice is. I made sure my sequences had appropriate sample numbers (to merge with attributes later in R). I trimmed the sequences so they matched in length. End gaps could be counted as the same length, but then you'll get lots of haplotypes that are simply different lengths of gaps at the end. I exported the data from Geneious as a .fasta file.
2. Creating the network
Now you have a .fasta file of sequences that are all the same length. I used code from this blog post to create the haplotype network. It worked great using functions in the R package pegas. The code there uses site to make up the slices of the pie, but you can also use other attributes (I used phenotype and transect) of the sampled individuals.
3a. Manually changing the colors
The haplotype network produced from step 2 has a rainbow color palette, which is pretty, but it may not fit with your desired color schemes or with black-and-white printing in a publication. Some of the colors can be hard to tell apart too. In my case, it was hard to interpret because I needed light and dark versions of two sets of birds within the haplotypes. I was having trouble with the igraph package that was suggested to edit colors, so eventually I decided to just export the figure as a scalable vector graphic (.svg).
I then edited the .svg file's colors in Inkscape, a free, open-source vector graphics editor. Once you open your figure in Inkscape, click on the figure. That selects it. Then you can right-click and find "ungroup" in the menu or go to the Object menu for "ungroup". Usually then you can select individual pieces of the figure, but if not, keep ungrouping pieces of the figure until you can.
Now, you should be able to grab pieces of the pie and change their color. You can do more than one by holding down the shift key while selecting additional pie slices and the legend (to make sure the legend color matches your pie slice color). Just double-click on the color you want in the bar on the bottom part of the screen. Repeat as needed for the other pie slices.
One problem I ran into was distinguishing a few of the colors on the original figure. You can use the ink dropper tool (press F7 or find it in the toolbar on the left side of the screen) to make sure you are correctly identifying particular colors as the same ones and not accidentally merging different sites or attributes in your final figure. By holding the ink dropper tool over a color, you show the color's hexadecimal code in a gray area below the color palette bar on the bottom of the screen.
From within Inkscape, you can then use "save as" to get your image in another vector graphic format (.ps or .eps) for publication, or use "export bitmap" (also in the File menu) to create a new raster graphic .png for publication or presentation.
3b. Updated 13 Feb. 2018: Automated colors!
I have figured out how to use the R package igraph to automate the coloring of the pie slices.
Unfortunately I haven't figured out how to put the tick marks back on for number of changes between haplotypes, but the line lengths are still proportional to number of changes. (If anyone knows how to do that, please let me know.)
Below is a complete example that will take you from creating the network to the final plot.
library(pegas)
library(igraph)
library(plyr)
library(reshape)
########################
#Step 1a. Load your alignment and use haploNet() to create the haplotype network.
#Load the pegas package sample data "woodmouse".
#This step is adapted from pegas help.
data(woodmouse)
set.seed(42)
x <- woodmouse[sample(15, size = 30, replace = TRUE), ]
h <- haplotype(x)
(net <- haploNet(h))
plot(net)
########################
#Step 1b. Have sites.
#I'm going to add in some arbitrary sample attributes that we'll use for pie chart testing.
#For your actual dataset, you would load a dataframe of localities for each sample.
#The samples and their sites should be in the same order as the samples in the file you used for haplotypes in 1a.
#Here, we randomly generate assignments to sites A, B, and C for the woodmouse dataset, which now has 30 samples.
sitenames <- c("A", "B", "C")
set.seed(84)
sites <- data.frame("site" = sample(sitenames,
size = 30,
replace = TRUE))
########################
#Step 2. Assign haplotypes to your site dataframe.
#This code is adapted from a blog post by Jimmy O'Donnell (jodonnellbio at gmail) with help from Kim Tenggardjaja.
#Original posting: http://jimmyodonnell.wordpress.com/2013/11/23/haplotype-networks-in-r-updated/
#Adaptations to this code by Claire Curry (curryclairem@gmail.com)
#Now, fill in the haplotypes for each site.
#You will have to do this with your real dataset.
#The site and haplotype dataframes must be in the SAME SAMPLE ORDER.
#Add empty column to sites dataframe for haplotypes
sites<-cbind(sites,
haplotype=rep(NA,
nrow(sites)))
#Assign haplotypes to the samples automatically using a loop
for (i in 1:length(labels(h))){
sites$haplotype[attr(h,
"index")[[i]]]<-i
}
########################
#Step 3. Convert to igraph format from haplonet.
#Here's my new adaptation to plot colors automatically in igraph, as suggested on the original blog post.
#Get igraph network
net.igraph <- as.igraph(net,
directed = FALSE, #Leave network arrows off as they are not relevant to our case.
use.labels = TRUE,
altlinks = FALSE) #only get main links between haplotypes or you'll end up with tons of extra lines
#Get the haplotype numbers in their weird order so you can order colors and sizes correctly.
newnums <- as.roman(as.character(V(net.igraph)$name))
V(net.igraph)$name <- newnums
########################
#Step 4.Count up haplotype frequencies and site frequencies.
#This code is adapted from a blog post by Jimmy O'Donnell (jodonnellbio at gmail) with help from Kim Tenggardjaja.
#Original posting: http://jimmyodonnell.wordpress.com/2013/11/23/haplotype-networks-in-r-updated/
#Adaptations to this code by Claire Curry (curryclairem@gmail.com)
#Count how many individuals for each haplotype
count.hap0<-ddply(sites,
.(haplotype),
summarise,
freq=length(haplotype))
#Be sure to add in our new ordering!
count.hap <- count.hap0[order(match(rownames(count.hap0),
newnums)),"freq"]
#for each plot, build frequency matrix that tells how to fill the pies by site frequency.
dfcount_site<-ddply(sites,
.(site, haplotype),
summarise,
freq=length(site))
dc.site00 <- cast(haplotype ~ site,
data = dfcount_site,
value = "freq",
fill = 0)
dc.site0 <-dc.site00
########################
#Step 5. Convert the site frequencies into the correct list format and the correct order to match the igraph object.
#Now, onto more igraph adaptations.
dc.site0$haplotype<-NULL #Remove the haplotype row before turning this into a matrix.
#Turn the haplotype frequencies into a matrix in the NEW IGRAPH ORDER.
dc.site1<-t(as.matrix(dc.site0[order(match(rownames(dc.site0),
newnums)),]))
#You must do this step to match the ordering of the cast dataframe haplotypes to the ordering used in igraph,
#otherwise the colors and sizes will be off.
#Then split the matrix out into a list.
dc.site <- split(dc.site1,
rep(1:ncol(dc.site1),
each = nrow(dc.site1)))
#Remember, if you go back to your haplotype counts to check that colors and sizes are correct,
#that we rearranged dc.site to be in the order that the haplotypes are stored
#You can check V(net.igraph)$name to see them again.
#dc.site0's haplotype column shows the haplotype numbers, but doing order(match() then puts dc.site1 and dc.site into
#the order the haplotypes are stored in the igraph network.
#Hence, we use the following step to make it more obvious by naming each list element with the haplotype number.
names(dc.site) <- V(net.igraph)$name
########################
#Step 6. Plot the network.
plot(net.igraph, #the igraph object is always a list of 10 so far as I can tell, regardless of how many haplotypes you used.
vertex.shape="pie",
vertex.pie = dc.site,
#vertex.pie specifies where you are getting the pie slice counts.
vertex.pie.color=list(c("black",
"orange",
"blue")),
#The colors are the number of categories you have, must be in a list, in the same order as your sites.
vertex.size = 5*(count.hap),
#number of samples for each haplotype, multiplied to make bigger if desired.
#vertex.label = NA)#, #for no vertex labels (ie no hapotype numbers added)
#vertex.label.cex = 1)#, #if you want bigger haplotype numbers.
vertex.label.dist = 2.5) #how far from pie you want the haplotype numbers)
#Add a legend.
legend(x= "bottomleft",
bty="n",
pt.bg=c("black",
"orange",
"blue"),
col="black",
pch=22,
legend=c("Site A",
"Site B",
"Site C"))
Subscribe to:
Posts (Atom)