Labels

Showing posts with label practical. Show all posts
Showing posts with label practical. Show all posts

Thursday, January 26, 2017

Sea Ice Animation

I just came across this animation this morning and I really like the use of polar coordinates to make the time axis effectively infinite. The animation is fun, and was created using the tools from processing.org. Processing is a suite of tools for creating visualizations and animations. There are many tutorials on the website, for anyone interesting in exploring it further.


Monday, November 14, 2016

Quickly Adding Depth to Flat Figures

Last week I attended a talk by Christopher Love, a faculty member at MIT. I noticed a simple visual effect he used several times in his presentation to give depth and dimension to what would otherwise be a flat figure.

On one slide, he illustrated a crowd of people as a way to talk about the effects of a treatment. The figure could have looked something like this, if he'd left it flat.

Now, if had been me, I'd probably have just left it like this. But not Dr. Love. He went the extra mile and added depth by changing the size and color. He made figures in the foreground bigger and darker, while figures in the background were smaller and lighter.

It takes 30 seconds to add these extra details, and the result is more pleasing and interesting. Now you have this same trick in your toolbox.



Monday, July 25, 2016

ggplot Extensions

If it wasn't clear before now, I'll just come out and say: I'm a huge fan of ggplot! And this week I became an even bigger fan. A friend forwarded a link to the official ggplot extensions page. Several plot types that were hard to generate before, are now extremely easy. New additions include a phylogenetic tree package, a creative time series package (for anyone tired of line plots), a network visualization tool,  and many others. I encourage you to check the extensions page regularly!

Example from the Time Series Extension


ggradar Example


Many of these extensions are not available for download through the RStudio Install Tool, but most are easy to install nonetheless. Here's a quick example getting the ggradar extension up and running.

First step, use the RStudio Install Tool to install "devtools" and "scales" (or, alternatively, run the command 'install.packages("scales")').

Second step, install the ggradar extension from the github repository using the 'devtools::install_github()" command:

devtools::install_github("ricardo-bion/ggradar", dependencies=TRUE)

Lastly, run some example code (available on our bitbucket repo):


And the result will be a fancy radar plot, which required no more than a few key strokes.

Friday, April 29, 2016

Comparing Visualization Libraries in Python

I just ran across a great post from the DataQuest blog comparing several plotting libraries in Python.

Highlights:
  • They don't explicitly give an intro to the Pandas package (a user-friendly data organization package with many features reminicent of those in R), but they do make use of it in all their examples, so it's helpful for those who aren't familiar with Pandas.
  • Examples building visualizations with MatPlotLib, Seaborn, Bokeh, Pygal, basemap, folium, and networkx. 
  • Example visualizations include histograms, bar charts, scatter plots, maps and network diagrams. 
They include all their data and code, so it's easy to get started with the examples they show. This is a great resource for finding the right Python tool for your project.


Tuesday, January 26, 2016

D3: Data-driven and Interactive Visualizations

D3.js is a JavaScript library for handling data and visualizing it. A carefully-crafted D3 visualization is, in my opinion, the most aesthetically stunning and informative way to display information. If you haven't been convinced of that yet, take some time to convince yourself by browsing this collection of examples. To sell it a little more, the NY Times makes use of D3-based visualizations, as does FiveThirtyEight.

Web Programming

So, you're sold, and you want to get your feet wet creating that beautiful graphic. How to get started?
First, D3--and JavaScript in general--is a web programming language, so you will struggle if you don't already have a working knowledge of HTML, SVG, CSS and JavaScript. You can pick up that working knowledge through many online tutorials, or a book from the library. My favorite source is W3Schools. I am, by no means, fluent in any of these languages, but to get started, it's enough to know how they are structured.
For example, HTML manages the layout of your content and forms the backbone of a webpage. SVG is a graphical format for making illustrations, with a mark-up structure similar to HTML. CSS can control visual formatting of the HTML elements. JavaScript is like other scripting languages (e.g. Python) but runs in a browser. JavaScript is what makes a webpage dynamic--taking user input, making real-time calculations, and modifying webpage content accordingly. D3 is a JavaScript library that makes it easier to load data and create/change visual elements based on that data.

Tutorials

Assuming you have (or will soon acquire) a working knowledge of basic web programming, there are some really great tutorials to get you started with D3. The best beginners tutorial ("Let's Make a Bar Chart") is by Mike Bostock (former graphics editor at the NY Times and developer of D3).

Beyond tutorials, Mike Bostock also developed a slick framework for sharing examples (http://bl.ocks.org/). Anyone can post their code to a GitHub Gist (a mini repository), and then point the bl.ocks.org/ URL to the Gist in order to display the example as a webpage. The really nice bit is that the code which generates the example is available to be learned from. After going through a couple of tutorials, I highly recommend browsing examples and looking through the code to see how they are accomplished.

Tips

Finally, it can be a bit daunting to get started with web programming. Displaying your draft web pages, debugging and sharing can all be hard to get working. Here's my way of doing things (which is by no means the only way):

  • First, I like to use an all-purpose text editor like Notepad++ to create and edit files.
  • To view a file in your browser, the file needs to be made available ("served" in a browser-readable format) by a server. I like to use the built-in Python SimpleHTTPServer. You'll need to have Python installed (I prefer to work with Python 2.7). Using the command terminal, navigate to the folder containing your HTML file and run the command "python -m SimpleHTTPServer". You can then view the webpage from  your browser by navigating to "http://localhost:8000/index.html" (assuming the file is named "index.html"). 
  • Your browser will have a set of developer tools which display errors generated by the code and the line number where errors were thrown, along with other helpful gadgets. 
Serving the file from  your own computer makes drafting and debugging very fast.
  • To share your finished examples, you can use a Gist and the bl.ocks.org system mentioned above. Your code will also work on GitHub Pages or BitBucket Pages. Of course, this will work with paid web hosting services or a lab website. 

Example

Here's an example I put together (my first D3 visualization ... something to make everyone else feel good about their first!).
I looked up the nutrition information for eight foods and compiled a .csv file. This is the data which guides the visualizations. The nutrition information for each food is displayed on a radar plot. The data points for each food item can be added or removed by clicking on the buttons at the top. 
The code for this example is available in our usual Bitbucket repository, and also a Gist.


Thursday, December 17, 2015

ggplot in Python

If you haven't already noticed (based on past posts), ggplot is, and will forever be, the best tool for visualizing data, producing the most beautiful results.

However, it gets awkward doing work in Matlab, Python (or even Excel), and then porting all the data over to R just for plotting purposes. It certainly doesn't make for a smooth workflow. Not easy to share with others. Not easy to remember how you did things months later. 

Now, at least Python users can enjoy some of the aesthetics of ggplot without needing to take a foray down the R rabbit hole (although, you may enjoy it down there ... we're certainly not discouraging anyone). And really, it all comes down to one line. Beautiful data, here we come.

Matplotlib

Wait, what? I thought this was a post about ggplot in Python, and here we're talking about matplotlib? The useful-but-ugly plotting package that has been available for eons? 
Well yeah, that's just it. A recent update to matplot lib added style sheets, one of which emulates ggplot. 

It's as simple as adding the lines:
import matplotlib.pyplot as plt
plt.style.use('ggplot')

Done. Nuff said about that.

Farkle Example

For the uninitiated, "Farkle" is not a curse word, but rather, an enjoyable game of chance involving six dice and requiring nerves of steel. To generate example data for our matplotlib-turned-ggplot plots, it seems good to also answer the age-old question of which Farkle strategy is most likely to win. 
In Farkle, each player is pitted against the others in a race to 10,000 points. Different combinations of dice earn points (e.g. four of a kind earns you 1,000 points, a 1-6 straight earns you 1,500 points, etc). The player starts by rolling all six dice. After rolling, the dice which earned points are removed, and the player can choose to 1) roll the remaining dice to earn more points or 2) keep the earned points and end their turn. The risk to re-rolling is that if no points are earned, all previous points from that turn are lost. The benefit of taking the risk is that if all dice produce points, then the player can start again rolling all six dice and accumulate an enormous score.
So, the age-old question: is it better to play conservatively or riskily? To accumulate lots of small scores, or hold out for the big scores?

The Farkle simulations are carried out with the Python script "farkle.py". 1,000 games were simulated using six strategies from "Coward" to "Crazy". The "Coward" won't roll any fewer than six dice. The "Crazy" will keep rolling no matter what until they've achieved at least 1,000 points, then they will stop if there is only one dice. The other levels are intermediate to these two. All the code for simulating and plotting can be found in the bitbucket repository.


We tracked the number of turns required to reach 10,000 points for each strategy 1,000 times. The average was pretty similar for all strategies except "Crazy", which tends to take much longer to reach 10,000 points. But who wants to look at a table of numbers? Let's visualize this bad boy.




So, you'll notice that a deft application of "syle.use('ggplot')" makes these matplotlib plots look like ggplots. You'll also notice that the "Careful" and "Cautious" strategies seems to strike the best balance between risk and reward, with an average of about 22 turns to reach 10,000 points (and the smallest standard deviations, suggesting consistency). That means that at the next family gathering, make it a rule to stop rolling if you only have 2 or 3 dice left. Make sure to encourage crazy behavior in your nieces and nephews.

Monday, November 9, 2015

GraPhlAn: Sorta Like Circos for Python

The right tool can save you a lot of time and effort. For those who need an easy-to-use Python tool for plotting data in a circular format, GraPhlAn is the way to go. Now, that may sound strangely specific ("Data in a circular format"?). Think of this as Circos for Python. Just as with Circos, GraPhlAn enables easy plotting on a circle, and like Circos, this tool was developed in order to make it easier to display biological information.

The authors went to great lengths to produce some excellent tutorials, and the package is easy to install and apply. The tool's intended use is to plot and annotate phylogenetic trees. While it's great at its job, it's capable of much more. Drawing another parallel (yes, a graphing pun) with Circos, while the original use was for genomics, circular plots are useful in many other contexts (see the Circos archive for examples of non-biological Circos applications). The same is true of GraPhlAn. All that's needed is to get rid of that phylogenetic tree in the middle, and you're ready to go.


Getting Rid of the Phylogenetic Tree


First, let's go back to how a GraPhlAn figure is made.
  1. Start with a Phylogenetic tree (accepts many formats). 
  2. Annotate the tree (using a annotation file with a GraPhlAn-specific format)
You may notice that there's not much room for "getting rid" of the phylogenetic tree. So, the next best thing is to hide it. Suppose you were going to plot some data on the 2016 Presidential Candidates or NBA player projections ... you need to start with a phylogenetic tree. What you'll do is create a tree with a branch for every element of your data (every presidential candidate or every NBA player). Something like the following:
Notice that it's literally just a list of the branches I want. "Branch1" could easily be Tyrone Corbin and "Branch2" could be Ron Harper.

Now, to make those branches invisible. In the beginning of the "annotations.txt", you just set the branches and markers to have thickness/size 0. It's easy as pie (aaaaaaand, a circle pun).

And the final result is a plot with no phylogenetic tree in the middle, but with lots of outer rings for plotting anything you want.

Plotting Anything You Want


The data is embedded in the annotation file. In this example, there are two ways to display numerical data (the GraPhlAn tutorials cover more ways, if you're interested): Heatmaps and Bars.

The "heatmap" rings are setup by setting the entire ring to the same color, and modulating the transparency of each element around the ring (less transparent = darker color):
In the first line, the ring transparency ("ring_alpha") for ring #2 (counting from inside to outside, where ring #1 is hidden), and branch "Branch51" is set to 0.005396837. In the second line, the color for ring #2 is set to #AAAA00 (that greenish-gold color). This is repeated for every branch.

The tall black bars around the outer edge are done in a different way. Here, the height of the ring elements are modulated:
Here, the height for the element of ring #5 that corresponds to "Branch51" is set to 2.3946... The default color is black. There's no reason you couldn't combine the heatmap and barchart methods to double-up the information content of each ring.

Having created an input "phylogenetic tree" file, and an accompanying annotations file, you're ready to plot. As per the GraPhlAn tutorial (and having installed GraPhlAn), you would then run the following code:
$ graphlan_annotate.py --annot annotations.txt custom_tree.txt no_tree.xml
$ graphlan.py no_tree.xml no_tree.png --dpi 300 --size 3.5

Resources

The code for this example is available at the Eats, Graphs and Leaves code repository.

For more GraPhlAn information, see the associated publication, and the Segata lab website.

Thursday, August 20, 2015

How to Follow a Journal's Artwork Guidelines

The time has finally come to submit that paper. You have done experiments, analyzed results in the context of previous work. You've written and re-written the text until you started having dreams about Microsoft Word. A final polishing step is to get your figures into shape. The Journal—which you hope will receive your work with great fanfare—will have specific artwork guidelines that must be followed before your masterpiece is acceptable for publication. In this post, we walk through the artwork guidelines from the Nature family of journals.

Different journals will have different specific guidelines, but the goal is generally the same: to ensure easy readability and visual appeal in the final, printed form. To achieve this, journals will seek to ensure high resolution, readable text, good contrast between colors, and appropriate figure sizes to fit the printed page.

Resolution


Resolution refers to the number of pixels used in the image. More pixels = finer details can be displayed = higher resolution. The rule of thumb is that higher resolution is better, but keep in mind that higher resolution also means larger files. If your figure meets the journal guidelines, that is sufficient; no need to overdo things.

The pixel density is only part of the story when an image is destined for a printed manuscript. In printed materials, the common measure of resolution is Dots Per Inch or DPI. This refers to the number of ink dots that can be fit within a one inch line. Digital images are made up of pixels, not ink dots, but even so, a digital image needs to be labeled with a target DPI, and adjusted to an appropriate pixel density, so that a printer knows what size and resolution to print.

That said, it's easy to increase the resolution of an image that you have drawn. In an illustration program such as Inkscape, the image is stored as a vector graphic (that is, as a set of shapes, not a set of pixels), which means that it can be converted to a pixel-based graphic format such as PNG, JPG, or TIFF, at any desired resolution. In Inkscape, for example, you simply choose the DPI you want as you're exporting the image. We have posted previously on a simple workflow for making publication-quality figures in Inkscape and GIMP.

As indicated in the Nature artwork guidelines, it is impossible to increase the resolution of a low resolution image. If you are using a photograph or pixel-based image from any camera or software program,  you need to ensure that the resolution is sufficiently high. This is true, even if you plan to embed the image into a larger figure. Most plotting software will have options for specifying the resolution of any saved images.

Size


Journals also have accompanying rules for text and line sizes that will be easily visible given the figure size and resolution guidelines. For example, Nature requires line weights between 0.25 pt and 1 pt in drawings. PNAS requires fonts to be between 6 and 12 pt. It's always easiest to start making your figures with these things in mind.

Colors


Color format refers to the way that colors are represented in a digital image. For example, RGB refers to the Red, Green, Blue color model, where the color of each pixel is represented as a mixture of red, green and blue (where the intensity of each is between 0 and 255). For example, the color white is (255,255,255). Pure blue would be (0,0,255). CMYK refers to the colors used in some printers: cyan, magenta, yellow, and key (black). A pixel's color in CMYK format will be represented by four numbers.

GIMP currently does not support CMYK-format images, although there is a plugin that might do the trick. Commercial software such as Adobe products can perform this conversion. There are online tools for this conversion, too. You may or may not have to convert something to CMYK, that's not the point here. The point is that a journal's artwork guidelines may ask for something specific for which you'll need to go find the right tool.

Format


This could probably go without saying, but there are many ways to represent digital images, and journals have their favorites. Make sure you choose an appropriate format. Most software packages will allow you to save your image in many different formats. GIMP is a useful tool for converting one format to another.

Overview


The key to simplifying the process of designing, polishing, and submitting your figures is to anticipate the journal guidelines. Once you know where you plan to submit your manuscript, look up their expectations for artwork. In general, the most important thing to anticipate early is the figure size (one column or two?). Font and line size are also good to keep in mind. Color and format can generally be left until the polishing stage.

Wednesday, July 15, 2015

Network Viz in Cytoscape

A few disclaimers before getting started: First, there are many tools for network visualization in R, Matlab, Python ... you name it. Cytoscape may just be the best, however. Second, Cytoscape can do far more than simply visualize your network-it can analyze it, too. This ability to analyze the network (identify connected components, node degree, etc.) enhances the types of visualizations you can perform. In this introductory tutorial, our focus is simply on making your network into a beautiful figure, but don't leave with the impression that Cytoscape is limited to making pretty pictures.

Which UVA Professors Have Published Together? A Co-Publication Network

It is interesting to visualize a community of people as a network, often done with data from social networking sites like Facebook. For this tutorial, I chose to visualize the connections between a group of 35 researchers at the University of Virginia.

While I won't go into the details of collecting the data, the code can be found here on the bitbucket repository. The gist is that a python script downloads the list of publications for each researcher in Pubmed. The coauthors on each publication are compiled into a list, and then searched to see if anyone authored papers with  each other. We also went one step further to check if any two researchers at UVA wrote papers with a shared coauthor. Two shortcomings which don't much matter here: Pubmed doesn't have every paper these authors wrote (or in some cases, any papers they wrote), so this doesn't give the full picture; and, because the method depends on name matching, if someone has the same name, or the same initials, there could be false positives. But, we just want to visualize it, errors and all. You start by formatting the data correctly.

Cytoscape accepts a few formats, and one of the simpler ways is to have a text file with a single line for each edge in the network. The format is <Source Node><delimiter><Edge Type><delimiter><Target Node>. In this network, it's <Author1><Tab><Number of Papers Written Together><Tab><Author2>.
The "sca1_2" stands for "shared co-author between authors 1 and 2". The edge type of -1 is to distinguish indirect edges from direct edges (which are positive).

Similarly, a node attributes file can be created which adds additional information about each node. The format is <Node Name><delimiter><Attribute>, like so:

Visualization in Cytoscape

First, you'll need to download and install Cytoscape. It requires up-to-date Java, so be prepared to install a couple of things before you're ready to roll.

Open Cytoscape

First things first, import your network:
Open From Network File "coauthorshipNetwork.tsv".
Show Text File Import Options and deselect "space" as a delimiter while keeping "tab".
Assign Source as column 1, Interaction as column 2, and Target as column  3.

Notice that the network is in a default style and layout. Change those immediately (defaults are not the way to impress):
In the Control Panel select the "Style" tab and change from default to "Solid".
Layout->yFiles Layout->Organic

Cytoscape allows a lot of flexibility in formatting the network appearance based on network attributes. For example, to make the node appearance dependent on whether the author is in our list, versus a common co-author that we're less interested in, we first need to add that information to the network:
File -> Import Table -> File "author_attributes.tsv".

Now, on to customizing your network appearance:
In the control panel, select "Node" style attributes.
For "Fill Color", set column to "Type", "Mapping Type" to "Discrete Mapping", "CommonCoAuthor" to grey and "MainAuthor" to yellow.
For "Size", "CommonCoAuthor" to 10 and "MainAuthor"to 60.
For "Label Font Size", "CommonCoAuthor" to 3 and "MainAuthor"to 30.

In the control panel, select "Edge" style attributes.
Set the "Stroke Color" to correspond to the interaction value, with a discreet mapping such that the indirect edges (value = -1) are light grey, and the direct edges (value > 0) are dark grey.
Set the edge "Width" to correspond to the interaction value, with a discreet mapping such that the indirect edges are width 1, and the direct edges are width 7.

Right click to add nodes. Select nodes and right click again to edit the node names. Using the "table panel", you can edit the attributes of the nodes and edges so that the styles you just set will apply. For example, you can set the new new nodes to be "MainAuthor" so that they are displayed big and yellow.

And you're off to a good start. Remember, Cytoscape is powerful and allows for a lot of analysis and infinite customization. Few things can get your audience interested as quickly as a beautiful network.

Monday, July 6, 2015

Turn-Key Polar Coordinates

In the search for new, interesting, or clear ways to visualize your data, consider the value of plotting things on a circle. Instead of a bar chart, a pie chart. Or instead of a line graph, a radar plot. The R package ggplot2 makes this easy as "pi" (forgive the pun) with the "coord_polar()" modifier. All the R code (it's not much) to reproduce these examples can be found at our bitbucket repository.

Observe a normal bar chart:

Treat the x-axis as a set of polar coordinates, and you now have a pie chart:


Similarly, observe a normal scatter plot:


Deftly re-plot while treating the x-axis as polar coordinates:



Check out the code, and you'll notice that the only extra step is to add the line specifying which axis should be treated as polar coordinates:

 
 # Polar Coordinates  
   
 library(ggplot2)  
   
 s = c("A","E","I","O","U")  
 random_data = data.frame(x = factor(sample(s, 50, replace=T)))  
   
 p = ggplot(random_data, aes(x=x)) +   
   geom_bar(width = 1, colour = "black")  
 print(p)  
   
 ggsave('normal_bar_chart.jpg')  
   
 p2 = ggplot(random_data, aes(x=x)) +   
  geom_bar(width = 1, colour = "black") +  
  coord_polar()  
 print(p2)  
   
 ggsave('polar_coordinates_bar_chart.jpg')  
   
   
 random_data2 = data.frame(x = runif(50, 0, 5), y = runif(50, 0, 10))  
   
 p = ggplot(random_data2, aes(x=x,y=y)) +   
   geom_point(size = 4, alpha=0.5)  
 print(p)  
   
 ggsave('scatter_plot.jpg')  
   
 p = ggplot(random_data2, aes(x=x,y=y)) +   
   geom_point(size = 4, alpha=0.5) +   
   coord_polar(theta="x")  
 print(p)  
   
 ggsave('polar_coordinates_scatter_plot.jpg')  
   

Wednesday, July 1, 2015

Circos and Shakespeare

You know those cool circular plots that manage to display every conceivable piece of data and still look classy? They've been displayed on the cover of more high profile journals than you can shake a stick at ... you know the ones I mean? Circos plots. If there is a social hierarchy among data visualization tools, Circos is arguably in the aristocracy. If you can produce a Circos plot from scratch with your own data, you are bound to get compliments (and acknowledgements from your audience such as "That's a Circos plot, isn't it? Nice.").

In order to earn the respect that comes from being a full-blown Circos wizard, there is a significant learning curve. The Circos website offers many tutorials, which we will not try to replicate here. Instead, we started out own journey up the Circos mountain, and documented our thoughts, feelings, and work. Sometimes it's helpful to have things said in a different way.

The Goal

First thing, let's take a look at what we're aiming for:

Around the circumference of the plot are 154 of William Shakespeare's sonnets. The block colors are assigned randomly. Red markers indicate where the word "love" is used, while blue markers indicate where the word "hate" is found. Black lines connect identical fragments of text of 12 characters or longer (excluding white space). Between the colored blocks and the labels are small histograms indicating the frequency of the letter "e" in 100 character windows of text.

Some things to notice:
  1. You can add as many layers as you like! There is very little stopping you from piling in every last scrap of data you have in increasingly complex concentric circles.
  2. There are many different tools for displaying data including scatter plots, histograms and line graphs, links, labels, and more. These can be arranged in concentric circles or in overlapping layers.
  3. All of this flexibility and power comes with some overhead cost. It's kind of complicated to make one of these. This is a tool for the serious scientific graphic designer.

Formatting the Data

All the data and code to accomplish this project can be found in our bitbucket repository.

The text for each sonnet was obtained freely from Project Gutenburg. In order to plot these sonnets, the first file you'll need is a "karyotype" file. The karyotype file defines the structure of the circumference of your plot. In this case, each sonnet is assigned to be a unique "chromosome". The structure of this file is pretty straightforward: chr - ID Label Start Length Color:
Next, the data files generally take an also straightforward format. For example, to indicate each occurrence of the word "love", a file has on each line: the chromosome ID (e.g. "son4"), the position of the word (start and end, which here we set both to be the start), and the value of the marker at that position (which we set all to zero, since the position matters here, not a measurement as in the next example).

The same thing is done for the frequency of the character "e" in each 100 character window. The chromosome ID is indicated with the beginning and end of the window, then the frequency (which corresponds to the histograms in the plot).

The links are defined using a format that includes a set of paired lines in the file. Each row in the file indicates an end of the link, provides information about which chromosome the link ends at, and what position within that chromosome.


All of these files are created using the cleverly-named Python script "parse_sonnets.py".

Plotting

Now we get to Circos. First, you'll need to download Circos and install any dependencies. Circos is based on Perl, so you'll need to obtain a Perl distribution if you don't already have one. For Windows users, Strawberry Perl works fine. Unix users probably already have Perl installed.

The actual Circos executable is found in the bin directory and is aptly named "circos". Attempting to run this the first time may unearth the Perl modules you're missing. CPAN has all of the needed dependencies for free, and they are easy to install.

The heart of the Circos plot is the configuration file, which is formatted as a markup language. Our file that generated the figure above is named "sonnets.conf". There are many intricacies and loads of flexibility built into this plotting resource, so we will just highlight the essentials:

Include the correct karyotype file to build the backbone of your plot.

Create the colored blocks and corresponding labels. In this case, these indicate the relative length of each sonnet (they're all about the same length, but they're different, we promise!). These are defined between the "ideogram" tags.

Add links between regions of identical text using the "links" tags. Notice that the "sonnet_overlaps.txt" file is included as the source of the data here.
Finally, the histogram (between the colored blocks and the labels) and the scatter plot (the markers indicating the position of the words "love" and "hate") are defined within the "plots" tags. Notice that the files "sonnet_love_occurrences.txt", "sonnet_hate_occurrences.txt", and "sonnet_E_frequency.txt" are included as the data source for each individual plot.
One everything is in place including your configuration file, karyotype file, and data files, all you need to do is run circos indicating the configuration file. On a Windows machine you would run a command like this:

perl circosPath\circos -conf sonnets.conf

Final Notes

As we mentioned, there is a whole universe of possibilities and custom solutions. Go play around with this code, follow the Circos tutorials, and find examples of previous work to inspire you. As an ending note, the Circos software outputs the plot as both a PNG file, and an SVG. This means that you can further customize these plots using GIMP and Inkscape. You'll be garnering glory and honor at the next poster session in no time!


Monday, June 22, 2015

Basic Figure Assembly and Polishing: A Workflow

As a new graduate student writing my first paper, I found myself confused and daunted by all the figure guidelines from the journal I hoped to publish in. What is dpi and how do I ensure that a figure has enough? How do I convert between a TIFF or a vector format like SVG or PDF? How do I ensure that the image colors are encoded as RGB values?

What about making clean, professional illustrations? Or assembling multi-panel figures? What about switching colors in an image? Or, the better question, how do I do any of these things without breaking the bank on Adobe products?

The answer to all these questions (at the very least) is in two programs: Inkscape and Gimp. Both are FREE and powerful enough to make beautiful, publication-quality art work.

In my mind, Inkscape is best for illustration and layout steps. It works with vector graphics under the hood, which can then be converted into a bitmap image later on. I mostly use Gimp for converting between file types (bitmap to TIFF, for example), changing color schemes, or general editing of non-vector images.

As a disclaimer, both of these software packages are extremely powerful and broad, and there is a whole world of things that they are capable of. The following workflow is just one example of how I go about making a figure for publication, and how I make use of these two pieces of software. The basic steps go like this:

  1. Create basic underlying figures using R, Matlab, or whatever plotting software is nearest to your heart.
  2. Create any illustrations, and figure out the layout of multi-panel figures, in Inkscape.
  3. Finalize the figure in Gimp, and export in the correct format.


Simple Figure Assembly in Inkscape

In this example, I make a simple two panel figure with a graph and an illustration.
First, produce a simple plot using the ggplot2 library in R. This image, and the R code to produce it, can be found here (along with all the files to complete this workflow).

For starters, open Inkscape and set the figure size by going to the File->Document Properties menu. Often journals give figure size guidelines, and this is where you can get started on the right foot. For this example, change the units to "cm", the width to 17.8 cm and the height to 8 cm.

Drag and drop the figure file "simple_plot.jpg" into the blank Inkscape document. Select the "embed" option, and click OK. The figure will appear much larger than the document, so you'll need to re-size. This can be accomplished by first selecting the plot by clicking on it, then either grabbing the arrows on the corners of the figure and dragging to re-size (be to keep the aspect ratio, hold the control key while dragging), or by typing the new sizes into the width "W" or height "H" boxes at the top of the screen (click the padlock symbol to lock or unlock the aspect ratio). In this case, I re-size to be 450 px wide. Notice that if you repeatedly click the plot, the arrows on the sides will toggle between size and rotation handles.



Next, we add sub-panel labels. This is accomplished by selecting the text object editing tool on the left-hand panel. When the object is selected in "text object editing" mode, it is possible to re-size the text area, change the font size, font attributes, etc. In this example, set the text to size 32 in the default font, and set to bold. When selected in the "select and transform objects" mode, you can move, copy/paste, rotate and re-size the text as though it were an image.



Copy and paste the "A" label once you've got the settings figured out, and move this copy of "A" over to the right-hand panel. Select the object in "text editing" mode, and replace the "A" with a "B". To make sure the "B" is lined up with the "A", select the "A", and check its position on the y-axis (in this case, 253.573 px). Re-select the "B", and manually type in the correct y-axis position.


Now, let's make a simple line drawing. The illustration capabilities of Inkscape extend far beyond what will be shown here. This should get you started though. First, draw two three circles, arranged as the points on a triangle. Select the "create circles, elipses and arcs" tool from the left-hand panel. Once you've drawn one, copy and paste it twice to get the other two identical circles. To select multiple objects at once, hold down shift while clicking multiple objects (or click and drag a box select around all the objects). Change the color through the Object->Fill and Stroke menu.



To make simple line, select the "Bezier curves and straight lines" tool from the left-hand panel. Click+control key will snap lines to angles. Click and drag will create curved line segments. Once again, the Object->Fill and Stroke menu allows you to edit line properties such as color and width. In this case, set the color to black, and the line width to 2 px. The "edit paths by node" tool allows you to rearrange the nodes in your line segments, and fiddle with the curvature in curves. There are also tools for rotating objects a fixed 90 degrees, or flipping to the mirror image vertically or horizontally.

If you want to control whether an object is below or above another, use the "lower selection to bottom" or "raise selection to top" tools. You can "group" objects using the Objects->Group tool, thus allowing them to be manipulated as a single object.

Once you're happy with the appearance of your figure, export the figure as a bitmap through the File->Export Bitmap menu. Export the page and choose the resolution. In this case, the journal probably specifies a minimum resolution, which we'll assume is 300 dpi. Note the figure dimensions when you select the resolution (in this case, the figure will be 2102 x 945 px). Click "Export", and you're done with the Inkscape portion.

Figure Finishing in Gimp


Now, open Gimp and create a new new document using File->New. Set the size to match the recently-exported bitmap "multi-panel_figure.png". Open the "Advanced Options" and set the resolution to 300 dpi on both axes. Click "OK", and the blank figure will open. Drag and drop the bitmap into this blank Gimp document. To export as a TIFF, navigate to File->Export, name the file "multi-panel_figure.tif", and select the file type as TIFF image. Sometimes journals will ask for LZW or some other TIFF compression format, which you will be given an option to select after clicking "Export".



At this point, unless I've done any other editing in Gimp, I close without saving. And voila, a publication-quality figure, with the correct dimensions and resolution.

There is lots more to learn as far as Inkscape illustration options go (the Filters are fun to play with), and Gimp can do way more than just convert images to the correct file type. But this is a starting place. Happy graphing.