Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Legend won't load #19

Closed
gbouras13 opened this issue Apr 10, 2023 · 2 comments
Closed

Legend won't load #19

gbouras13 opened this issue Apr 10, 2023 · 2 comments
Labels
question Further information is requested

Comments

@gbouras13
Copy link

gbouras13 commented Apr 10, 2023

Hi @moshi4 ,

Thanks for making such an amazing tool, pyCirclize is great and very simple to use.

I am trying to plot a circular phage genome so I can add it as an option in my program pharokka, mostly following your tutorials in the docs, but the legend won't load no matter what I try. Any ideas what could be causing the issue?

I'm using v 0.3.1.

The code is:

from pycirclize import Circos
from pycirclize.parser import Gff
from pycirclize.parser import Genbank
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import os
import numpy as np



# Load GFF file

def create_plot(out_dir, prefix, plot_name):
    # read in gff file
    gff_file =  os.path.join(out_dir, prefix + ".gff")
    gff = Gff(gff_file)

    # Load Genbank file
    gbk_file = os.path.join(out_dir, prefix + ".gbk")
    # get only to range of gff - as by default gbk takes all contigs, gff only the first
    gbk = Genbank(gbk_file, max_range = gff.range_size)

    # instantiate circos
    circos = Circos(sectors={gbk.name: gbk.range_size})
    #circos.text(plot_name, size=16)

    sector = circos.get_sector(gbk.name)
    cds_track = sector.add_track((90, 100))
    cds_track.axis(fc="#EEEEEE", ec="none")
    # Plot forward CDS
    cds_track.genomic_features(
        gff.extract_features("CDS", target_strand=1),
        plotstyle="arrow",
        r_lim=(95, 100),
        fc="salmon",
    )
    # Plot reverse CDS
    cds_track.genomic_features(
        gff.extract_features("CDS", target_strand=-1),
        plotstyle="arrow",
        r_lim=(90, 95),
        fc="skyblue",
    )
    # Extract CDS product labels
    pos_list, labels = [], []
    for f in gff.extract_features("CDS"):
        start, end = int(str(f.location.end)), int(str(f.location.start))
        pos = (start + end) / 2
        label = f.qualifiers.get("product", [""])[0]
        if label == "" or label.startswith("hypothetical") or label.startswith("unknown") :
            continue
        if len(label) > 25:
            label = label[:25] + "..."
        pos_list.append(pos)
        labels.append(label)
    # Plot CDS product labels on outer position
    cds_track.xticks(
        pos_list,
        labels,
        label_orientation="vertical",
        show_bottom_line=True,
        label_size=7,
        line_kws=dict(ec="grey"),
    )

        # Plot GC content
    gc_content_track = sector.add_track((50, 65))

    pos_list, gc_contents = gbk.calc_gc_content()
    gc_contents = gc_contents - gbk.calc_genome_gc_content()
    positive_gc_contents = np.where(gc_contents > 0, gc_contents, 0)
    negative_gc_contents = np.where(gc_contents < 0, gc_contents, 0)
    abs_max_gc_content = np.max(np.abs(gc_contents))
    vmin, vmax = -abs_max_gc_content, abs_max_gc_content
    gc_content_track.fill_between(
        pos_list, positive_gc_contents, 0, vmin=vmin, vmax=vmax, color="black"
    )
    gc_content_track.fill_between(
        pos_list, negative_gc_contents, 0, vmin=vmin, vmax=vmax, color="grey"
    )

    # Plot GC skew
    gc_skew_track = sector.add_track((35, 50))

    pos_list, gc_skews = gbk.calc_gc_skew()
    positive_gc_skews = np.where(gc_skews > 0, gc_skews, 0)
    negative_gc_skews = np.where(gc_skews < 0, gc_skews, 0)
    abs_max_gc_skew = np.max(np.abs(gc_skews))
    vmin, vmax = -abs_max_gc_skew, abs_max_gc_skew
    gc_skew_track.fill_between(
        pos_list, positive_gc_skews, 0, vmin=vmin, vmax=vmax, color="olive"
    )
    gc_skew_track.fill_between(
        pos_list, negative_gc_skews, 0, vmin=vmin, vmax=vmax, color="purple"
    )

    # Plot xticks & intervals on inner position
    cds_track.xticks_by_interval(
        interval=5000,
        outer=False,
        show_bottom_line=True,
        label_formatter=lambda v: f"{v/ 1000:.1f} Kb",
        label_orientation="vertical",
        line_kws=dict(ec="grey"),
    )

    # # Add legend
    handle = [
        Patch(color="skyblue", label="Forward CDS"),
        Patch(color="salmon", label="Reverse CDS"),
        Line2D([], [], color="black", label="Positive GC Content", marker="^", ms=6, ls="None"),
        Line2D([], [], color="grey", label="Negative GC Content", marker="v", ms=6, ls="None"),
        Line2D([], [], color="olive", label="Positive GC Skew", marker="^", ms=6, ls="None"),
        Line2D([], [], color="purple", label="Negative GC Skew", marker="v", ms=6, ls="None")
    ]

    fig = circos.plotfig()

    _ = circos.ax.legend(handles=handle, 
                         bbox_to_anchor=(0.9, 0.475),  
                         fontsize=8)
    
    # Add legend


    circos.savefig(savefile = os.path.join(out_dir,  "pharokka_plot.png"), dpi = 600)

pharokka_plot

I've attached an example plot too.

George

@moshi4
Copy link
Owner

moshi4 commented Apr 10, 2023

Hi @gbouras13,

Thank you for your interest in pyCirclize.

When plotting the legend, you cannot use circos.savefig().
Please use fig.savefig() of the matplotlib Figure object instead, as follows.

-    circos.savefig(savefile = os.path.join(out_dir, "pharokka_plot.png"), dpi = 600)
+    fig.savefig(os.path.join(out_dir, "pharokka_plot.png"), dpi=600)

I didn't use fig.savefig() in the jupyter notebooks docs, so it might have been a bit confusing. My apologies.
I will add a note to jupyter notebooks about fig.savefig() when plotting a legend in the next release.

@gbouras13
Copy link
Author

Thanks mate, this fixed it perfectly.

George

@moshi4 moshi4 added the question Further information is requested label May 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants