Search code examples
pythontreedrawbiopythonphylogeny

In python, how can I change the font size of leaf nodes when generating phylogenetic trees using Bio.Phylo.draw()?


I am using the Phylo package from Biopython to create phylogenetic trees.

For big trees, I need to decrease the fontsize of the leaf nodes. It has been suggested to change matplotlib.pyplot.rcParams['font.size'] but this only allows me to change axes names and titles, as Phylo defines its own font sizes. I can not change Phylo source code as I am using it at the University. Defining figures or axes is not an option as Phylo.draw() creates its own.

Does anyone have any suggestions on how to solve the problem, maybe stretching the y-axis?

So far I was using the following code to produce the tree:

import matplotlib
import matplotlib.pyplot as plt
from Bio import Phylo
from cStringIO import StringIO

def plot_tree(treedata, output_file):

    handle = StringIO(treedata) # parse the newick string
    tree = Phylo.read(handle, "newick")
    matplotlib.rc('font', size=6)
    Phylo.draw(tree)
    plt.savefig(output_file)

    return

Plot


Solution

  • Phylo.draw() can take the axes as an argument. From the method's documentation in Biopython you can read the following

    axes : matplotlib/pylab axes If a valid matplotlib.axes.Axes instance, the phylogram is plotted in that Axes. By default (None), a new figure is created.

    This means that you can load your own axes with your size of choice. For example:

    import matplotlib
    import matplotlib.pyplot as plt
    from Bio import Phylo
    from io import StringIO
    
    def plot_tree(treedata, output_file):
        handle = StringIO(treedata)  # parse the newick string
        tree = Phylo.read(handle, "newick")
        matplotlib.rc('font', size=6)
        # set the size of the figure
        fig = plt.figure(figsize=(10, 20), dpi=100)
        # alternatively
        # fig.set_size_inches(10, 20)
        axes = fig.add_subplot(1, 1, 1)
        Phylo.draw(tree, axes=axes)
        plt.savefig(output_file, dpi=100)
    
        return