R code to generate a phylogeny with associated trait values

The main content of this post is, as the title says, some R code that can be used to generate an image of a phylogeny with representations of trait values of the tips.

But first, some back-story: earlier this year, U of M Plant Biology grad student Derek Nedveck spent about an hour telling me about the virtues of R, the knitr package, open lab notebooks, and replicable science. I enjoyed the conversation but put it aside at the time, mainly since I wasn’t actively working on any particular project (I had just graduated, ok?) and had no knowledge of R.

I’ve learned quite a lot since then, thanks mainly to encouragement from my mentors at XTBG a whole lot of phylogeneticsinR tutorials (and a whole lot more I haven’t linked here — fear not, a more comprehensive list of tutorials I used is on its way). I’ve also been thinking a good bit about transparency in the scientific process, thanks mainly to that conversation with Derek and the awesome folk at rOpenSci. It’s time to put the thoughts into action.

Although I don’t think that this code I am publishing in this post is very valuable as code, I do think that getting into a habit of writing clean code and sharing it with other scientists is important– at least, it is valuable for me personally. As I mentioned above, I taught myself a whole lot of R by using various tutorials that some wonderful people have developed, and will be pleased if I can contribute to this resource over the coming years. I feel like I am  taking an important first step by writing this post: I have learned how to use knitr, become confident about sharing code I wrote (more or less), and have, in a very very very small way, contributed to the community from which I got so much a few weeks ago.

For some background, this is code I wrote for our Ficus leaf trait project at AFEC, based on a small script originally written by Masatoshi Katabuchi (Thanks!! I hope you don’t mind my putting this up here for some reason…). Incidentally, the presentation based on the AFEC project can be accessed here.

I plan on using this code when I have a phylogeny and want to display some relevant traits of the taxa at the tip – here, the traits are continuous, but this can be easily changed for discrete traits. Lots of people probably have code for this sort of thing already, but if feel free to use this if you wish. If you do use it, please contact me – I’d love to know if what I am doing is useful!

Please excuse the crappy formatting in the code as displayed by WordPress. Don’t know how to make it look prettier.

Here goes.

FicusTree <- read.nexus("pruned_tree.nex")
# pruning the tree to remove the outgroup taxa
FicusTree <- drop.tip(FicusTree, c("Antiaropsis_decipiens", "Castilla_elastica", 
    "Poulsenia_armata", "Sparattosyce_dioca"))

#Unfortunately, this code requires that the trait values are ordered according their order in the phylogeny (i.e. if “Species c” is at the top of the phylogeny, followed by “Species F,” then the first two rows in the data table should be “Species c” and “Species F”). I am trying to write some code that doesn't require this

n.sp <- 30  #number of taxa in your phylogeny

# extract the colums we want to work with as vectors:
sla <- TraitVal$sla
# the current version of the code requires this vector to be reversed.
sla <- rev(sla)
toughness <- TraitVal$toughness
toughness <- rev(toughness)
area <- TraitVal$area
area <- rev(area)

n.traits <- 3  #number of traits you want shown

par(mfrow = c(1, 2))
par(mar = c(0, 0, 2, 0))

plot(FicusTree, show.tip.label = T, cex = 0.75)

plot(rep(1:n.traits, each = n.sp), 
rep(1:n.sp, n.traits), xlim = c(0, n.traits + 
    1), axes = F, ylab = "", xlab = "", type = "n")
abline(h = 1:n.sp, col = "gray75")
abline(v = 1:n.traits, col = "gray75")
axis(1, at = 1:n.traits, labels = c("SLA", "Area", "Toughness"), side = 3, col = "white", 
    cex.axis = 1)
points(rep(1:n.traits, each = n.sp), rep(1:n.sp, n.traits), xlim = c(0, n.traits + 
    0.25), pch = 21, col = "darkgreen", cex = (c(sla/100, area/100, toughness/500)))

Here’s the output:


This zip file contains some dummy files (a phylogeny, data table, and R code). You will be redirected to a FigShare file — figured I’d try that out now too!

Ok! That’s it. Writing this certainly has been a very useful exercise for me; with any luck, it’ll help someone else too.

By the way, I have a separate .html version of this code that knitr actually generated. As I now understand, WordPress can’t handle uploading html files, so if anyone has read this far and has advice on this, please do let me know. I plan to eventually migrate away from WordPress — that move may come sooner than later now.


Looking for citizen science-y projects to join!

I’m looking for opportunities to collaborate on crowd-funded ecology/evolution-related science! And given that SciFund project 4 was just announced, I figured that now is be a good time to write about this. I’ll repeat this at the bottom of this post, but if you have any idea for a project that has a strong citizen-science component and need some supporting manpower, please do let me know.

IMG_2284I’ve been thinking a lot about crowd-funded science quite a lot in the past few weeks (many thanks to my brother Gautam for starting a lot of discussions with me about this that got me to seriously think!), so I was very excited to read about the freshly-announced 4th round of SciFund. There’s a lot of good writing about the role of crowd-funding in science, especially in ecology/evolution (e.g. this article in TREE and this blog post at the Perlstein lab), so I won’t attempt to write about its virtues in general. I will just say that I am interested in doing some crowd-funded science for a couple of reasons:

  • There’s a lot of “non-scientists” who are deeply interested in scientific research. My father is a prime example of this: despite being far away from the ivory tower, he is
    constantly reading about basic scientific research, and has contributed a lot to citizen-science initiatives like the Zooniverse Notes From Nature herbarium sheet digitization project. Engaging with these people in any way possible is a no-brainer for me.
  • I think there’s a lot of good projects that can be done using data that is already publicly available data. The cost of these projects is probably pretty low given that the data collection can all be done using just a computer with a reliable internet collection, so why not do it crowd-funded instead of developing cumbersome grant applications that probably take forever to get processed?
  • As Dr. Perlstein wrote (see above), there’s a lot of “academic conservatism” and “ideological resistance” among established scientists to the idea of crowd-funded science in the current academic community. I fancy myself a rebellious trend-bucking anti-institutionalist (…), so this is reason enough for me to embrace crowd-funded science.

Anyway, enough justifications…

I’m really into this concept, I am not close to being able to lead anything alone right now. I have no institutional backing, my plans over the next few years aren’t concrete, and most importantly, I don’t have the experience it takes to develop a strong research project. BUT, I do have a lot of energy, am excited about bringing science out of the lab, and want to embrace the new era of science as much as I can. I am always happy to put a lot of energy into projects I think are worthwhile, so if you have an idea but need an excited young go-getter to put some energy into it, do let me know!! You can contact me at gaurav.kandlikar@gmail.com.

I am hopeful but not confident that something comes out of this!

Alfred Russell Wallace on Durian, the “King of Fruits”

In Dr. Richard Corlett’s first talk at AFEC, he gave a broad overview of the biogeography of Tropical East Asia (conveniently, TEA). During the talk, he cited Alfred Russell Wallace extensively, and said that he was inspired to travel to TEA from England after reading Wallace’s writing. Since then, I’ve wanted to read The Malay Archipelago (full text here), and I finally got a start on it during my long return journey from China. As you might imagine, it’s a wonderful book for all sorts of reasons. It’s too good to not share, so I’ll probably be posting a lot of different sections as I read through it.

To begin, here is Wallace’s eloquent eulogy for the Durian:

“The banks of the Sarawak River are everywhere covered with fruit trees, which supply the Dyaks with a great deal of their food. The Mangosteen, Lansat, Rambutan, Jack, Jambou, and Blimbing, are all abundant; but most abundant and most esteemed is the Durian, a fruit about which very little is known in England, but which both by natives and Europeans in the Malay Archipelago is reckoned superior to all others. The old traveller Linschott, writing in 1599, says: “It is of such an excellent taste that it surpasses in flavour all the other fruits of the world, according to those who have tasted it.” And Doctor Paludanus adds: “This fruit is of a hot and humid nature. To those not used to it, it seems at first to smell like rotten onions, but immediately when they have tasted it, they prefer it to all other food. The natives give it honourable titles, exalt it, and make verses on it.” When brought into a house the smell is often so offensive that some persons can never bear to taste it. This was my own case when I first tried it in Malacca, but in Borneo I found a ripe fruit on the ground, and, eating it out of doors, I at once became a confirmed Durian eater. 

The Durian grows on a large and lofty forest tree, somewhat resembling an elm in its general character, but with a more smooth and scaly bark. The fruit is round or slightly oval, about the size of a large cocoanut, of a green colour, and covered all over with short stout spines the bases of which touch each other, and are consequently somewhat hexagonal, while the points are very strong and sharp. It is so completely armed, that if the stalk is broken off it is a difficult matter to lift one from the ground. The outer rind is so thick and tough, that from whatever height it may fall it is never broken. From the base to the apex five very faint lines may be traced, over which the spines arch a little; these are the sutures of the carpels, and show where the fruit may be divided with a heavy knife and a strong hand. The five cells are satiny white within, and are each filled with an oval mass of cream-coloured pulp, imbedded in which are two or three seeds about the size of chestnuts. This pulp is the eatable part, and its consistency and flavour are indescribable. A rich butter-like custard highly flavoured with almonds gives the best general idea of it, but intermingled with it come wafts of flavour that call to mind cream-cheese, onion-sauce, brown sherry, and other incongruities. Then there is a rich glutinous smoothness in the pulp which nothing else possesses, but which adds to its delicacy. It is neither acid, nor sweet, nor juicy; yet one feels the want of none of these qualities, for it is perfect as it is. It produces no nausea or other bad effect, and the more you eat of it the less you feel inclined to stop. In fact to eat Durians is a new sensation, worth a voyage to the East to experience.

When the fruit is ripe it falls of itself, and the only way to eat Durians in perfection is to get them as they fall; and the smell is then less overpowering. When unripe, it makes a very good vegetable if cooked, and it is also eaten by the Dyaks raw. In a good fruit season large quantities are preserved salted, in jars and bamboos, and kept the year round, when it acquires a most disgusting odour to Europeans, but the Dyaks appreciate it highly as a relish with their rice. There are in the forest two varieties of wild Durians with much smaller fruits, one of them orange-coloured inside; and these are probably the origin of the large and fine Durians, which are never found wild. It would not, perhaps, be correct to say that the Durian is the best of all fruits, because it cannot supply the place of the subacid juicy kinds, such as the orange, grape, mango, and mangosteen, whose refreshing and cooling qualities are so wholesome and grateful; but as producing a food of the most exquisite flavour, it is unsurpassed. If I had to fix on two only, as representing the perfection of the two classes, I should certainly choose the Durian and the Orange as the king and queen of fruits.

The Durian is, however, sometimes dangerous. When the fruit begins to ripen it falls daily and almost hourly, and accidents not unfrequently happen to persons walking or working under the trees. When a Durian strikes a man in its fall, it produces a dreadful wound, the strong spines tearing open the flesh, while the blow itself is very heavy; but from this very circumstance death rarely ensues, the copious effusion of blood preventing the inflammation which might otherwise take place. A Dyak chief informed me that he had been struck down by a Durian falling on his head, which he thought would certainly have caused his death, yet he recovered in a very short time.

Poets and moralists, judging from our English trees and fruits, have thought that small fruits always grew on lofty trees, so that their fall should be harmless to man, while the large ones trailed on the ground. Two of the largest and heaviest fruits known, however, the Brazil-nut fruit (Bertholletia) and Durian, grow on lofty forest trees, from which they fall as soon as they are ripe, and often wound or kill the native inhabitants. From this we may learn two things: first, not to draw general conclusions from a very partial view of nature; and secondly, that trees and fruits, no less than the varied productions of the animal kingdom, do not appear to be organized with exclusive reference to the use and convenience of man.”


SHOCKINGLY, neither the frozen durian I’ve had in Minnesota nor the durian flavoured McFlurry I was given in Singapore did this king of fruits much justice. I guess I need to get back to TEA and experience it correctly. But maybe I won’t be able to any way, given the apparent repulsion to the King.

Visit Wallace Online for a complete set of Wallace’s writing!

And finally, I want to thank Dr. Corlett for inspiring me to finally read Wallace. I enjoy Dr. Corlett’s writing very much as well (what’s not to love about solid science combined with the perfect amount of wit and “snark?”) — here’s his writings on google scholar.

Early thoughts about AFEC

So I wasn’t true to myself about writing during my sojourn to Xishuangbanna — I’ll chalk that up to being busy all day from about 8 am to 10 pm, and also to honest-to-goodness laziness. Anyway, I’ll write to reflect on my experiences now.

First off, general impressions: This was my first real field course, and it was everything I had expected and a lot more. Over the six weeks, I became part of a “community of learners.” We learned together, worked together, and played together. Next time I go on a field course, I will try to leave a week or two between the end of the course and my return itinerary — I will definitely find some way to spend that time with my new friends.

AFEC participants at the CTFS plot in Bubeng

XTBG itself is a wonderful community in a wonderful place. All of our instructors, from our “core instructors” to the graduate students that ran Practical sessions, were tremendously knowledgeable, enthusiastic, and engaging. Everyone really invested a lot of effort and time in our education, and I hope that I can meet their expectations of me throughout my career.

Dr. Richard Corlett leading a discussion about frugivores


Now for some notes of appreciation:

Special thanks to Drs. Eben Goodale and Kyle Tomlinson (boring Linked In link–is there anything better? EDIT: Kyle has sent me a new link to his Google sites page!), who taught the Statistics/R modules. As if teaching these things isn’t hard enough to begin with, Eben and Kyle had to do this after dinner, from 6.30 to 9pm every day for the first few weeks, at a time when all of us were getting tired from a long day of lectures and ready for  bed. Despite this, they did a really nice job with the lectures and practicals. I had never used R for anything meaningful before the course, but by the end of it, I was comfortable whipping together scripts to generate generalized linear models or a picture of a phylogeny with trait labels at the tips. I fully attribute this development to the wonderful introduction to statistics and R that Eben gave us and the clear introduction to sophisticated statistical methods that Kyle presented.

Thanks also to Drs. Alice Hughes and Uromi Goodale, who were wonderful mentors on… pretty much everything. Both of them repeatedly gave really helpful advice  on everything from statistical tools to where we could find some interesting food in town.  When helping us design our independent research projects, Uromi and Alice perfectly demonstrated what it means to be a scientific naturalist — a person with “deep and broad familiarity with one or more groups of organisms or ecological communities, who can draw on her knowledge of systematics, distribution, life histories, behavior, and perhaps physiology and morphology to inspire ideas, to evaluate hypotheses, to intelligently design research with an awareness of organisms’ special peculiarities.” Perhaps more importantly, the energy and enthusiasm that Alice and Uromi brought to every conversation was contagious, and I never felt tired after talking to them. I’ve said it before, and I’ll say it again: this is exactly what I hope to grow into over the years.

And finally, a shout-out to my independent project teammates : Zeng Si-Jin, Wu Wei-Huan, Nguyen Huyen, and Yao Xin. Our combined hard work led us to being named the “Best Presentation” at the AFEC Symposium, and earned us whatever glory the title carries. All of these guys were really great to work with. I only hope that they feel the same way about me.

Ficus group (AFEC 2013 at XTBG)

Ficus team, AFEC 2013, at XTBG “coffee lounge”

In appreciation of October — Autumnal Tints

I was writing about the science of leaf color change, but that can wait. Instead, here’s text from Thoreau’s ode to October. Read this, then immediately go out and enjoy the view. It’s long but worth it. Here’s the .pdf of the essay if you prefer to read it away from the distractions of the internet.

Autumnal Tints
by H. D. Thoreau

“October is the month of painted leaves. Their rich glow now flashes round the world. As fruits and leaves and the day itself acquire a bright tint just before they fall, so the year near its setting. October is its sunset sky; November the later twilight.” 

Europeans coming to America are surprised by the brilliancy of our autumnal foliage. There is no account of such a phenomenon in English poetry, because the trees acquire but few bright colors there. The most that Thomson says on this subject in his “Autumn” is contained in the lines,

“But see the fading many-colored woods,
Shade deepening over shade, the country round
Imbrown; a crowded umbrage, dusk and dun,
Of every hue, from wan declining green to sooty dark”:—

and in the line in which he speaks of

“Autumn beaming o’er the yellow woods.”

The autumnal change of our woods has not made a deep impression on our own literature yet. October has hardly tinged our poetry.

A great many, who have spent their lives in cities, and have never chanced to come into the country at this season, have never seen this, the flower, or rather the ripe fruit, of the year. I remember riding with one such citizen, who, though a fortnight too late for the most brilliant tints, was taken by surprise, and would not believe that there had been any brighter. He had never heard of this phenomenon before. Not only many in our towns have never witnessed it, but it is scarcely remembered by the majority from year to year.

Continue reading

National park musings

I just watched a National Geographic documentary about Yosemite (Netflix, Nat Geo channel — link not working for me). This was the first Nat Geo documentary I’d seen in a very very long time. I’d forgotten how incredible these documentaries are, and how important they were in getting me interested in nature. Although nature was all around me when I was growing up in India, being in the urban jungle that is Hyderabad meant that I didn’t really have much exposure to pristine, impressive nature. I got my fix for that from the Jeff Corwin Experience, watching the quirky host entering the forests of Borneo, deserts of Arizona, and rivers of South America. Anyway, the Jeff Corwin Experience deserves its own post, which I will write in due time.

Some thoughts about that Yosemite documentary:

Rock climbers are cray. I’d never think of climbing El Capitan, which is essentially a rock wall that extends almost a whole kilometer into the sky, but apparently its done pretty often. Here’s a video taken by a climber from the top of the “Texas Flake,” which is a large chunk of granite slowly being separated from the body of El Capitan:

The National Geographic documentary I’ve linked to above has footage of something called the “King Swing,” in which climbers have to run across the face of the wall to get from one “track” to another. It’s at around minute 29 — I’ll try to get a video of that up.

I hadn’t had enough fun by just watching the documentary, so I decided to play a little bit more with Google trends. Here’s some cool, somewhat inexplicable trends:

Screen Shot 2013-10-06 at 10.22.43 PM The line in yellow shows hits for the Grand Canyon. The peak in late June 2013 lines up with Nik Wallenda tightrope-walking across the canyon (how do people pull this stuff off?!). For the sake of accuracy — the walk wasn’t over the canyon in the Grand Canyon National Park, because the park service wouldn’t’ allow it. The rope was actually in Navajo nation’s land (source).

The blue shows searches for Yellowstone. I had assumed that Yellowstone would be more popular than Yosemite, and with some exceptional time points, this seems to be true.

Red shows Yosemite. The peak in August 2013 lines up with the fires that ran across the park. I assume that the last peak in October 2013 is due to people interested in the status of the park during the big bad shutdown. But why don’t we see as dramatic a peak in either of the other lines? A google news search for Yosemite doesn’t suggest that it has been in the national press any more than the other parks. Is Yosemite just that emblematic to the US, is it the “go-to” national park?

Here’s a chart showing number of visitors to the top 10 US National Parks (Source: the National Parks Conservation Association, since the National Park Service website is still down — oh, the shutdown woes!):

Screen Shot 2013-10-07 at 9.30.47 AM Ok, so Yosemite gets <40% of the visitors that the Great Smokeys get. Again, the google search trends don’t reflect these numbers:

Screen Shot 2013-10-07 at 9.32.04 AM

And a graph of just “Great Smoky,” so that the scale isn’t dominated by the other things:

Screen Shot 2013-10-07 at 10.44.02 AM

As before, yellow, blue and red show GC, Yellowstone and Yosemite; “Great Smoky” is in green. I really don’t have any idea of what is going on here. How come GS has ~3x the visitors of yellowstone, but 1/10th the relevance on google searches? Could it be that a lot of the visitors to the Smokys are locals who don’t ever feel the need to look it up on the internet before planning a trip? There’s a definite peak in searches for “Great Smoky” in the past week, but as shown above, the absolute numbers pale in comparison to the other parks.

There must be something I am missing when I expect the parks with the highest visitors (by a large margin, at that) to be the most searched park. Any ideas welcome.

And finally, because big trees are indeed rock and roll, here’s some solid PBS coverage of the Giant Sequoia groves in Yosemite and how the recent Rim Fire and future fires might impact them (link):

I’ll write  about fire ecology some time soon (AKA once I learn more about it!).

Shutdown woes

Via Jonathan Eisen: a gallery of the “government shutdown of science” (easy-to-view picasa gallery here)

Some more contributions:

This message brought to you from the NMNH L.A.B director. Silly scientists, expecting permission to continue their research!
Screen Shot 2013-10-02 at 8.48.17 AM
Status of the fellowship I’ve spent the better part of last month working on: unknown (not that I even remotely regret having spent all that time) 
Gotta start thinking about those alternative funding sources…