For generating plots

export_to_html(fig, div_id)

Export plotly graph to html format

Parameters:
  • fig (Figure) –

    Plotly figure to export

  • div_id (str) –

    String to use as the plot's div id.

Returns:
  • str( str ) –

    HTML string with plot

Source code in microview/plotting.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def export_to_html(fig: Figure, div_id: str) -> str:
    """
    Export plotly graph to html format

    Args:
        fig (Figure): Plotly figure to export
        div_id (str): String to use as the plot's div id.

    Returns:
        str: HTML string with plot
    """
    config = {"modeBarButtonsToRemove": ["zoom", "select", "lasso2d"]}

    return io.to_html(
        fig,
        full_html=False,
        include_plotlyjs=False,
        include_mathjax=False,
        div_id=div_id,
        config=config,
    )

generate_taxo_plots(tax_data, contrast_df=None, output_path=None)

Get all taxonomy plots

Master function to generate all plots to be used in the final report.

Parameters:
  • tax_data (dict) –

    Dict resulting from microview.parse_taxonomy.get_tax_data

  • contrast_df (DataFrame, default: None ) –

    Dataframe with sample names and contrasts, if available.

Returns:
  • dict( Dict ) –

    Dict containing all plots, one for each key.

Source code in microview/plotting.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def generate_taxo_plots(tax_data: Dict, contrast_df=None, output_path=None) -> Dict:
    """
    Get all taxonomy plots

    Master function to generate all plots to be used in the final report.

    Args:
        tax_data (dict): Dict resulting from
            microview.parse_taxonomy.get_tax_data
        contrast_df (pd.DataFrame): Dataframe with sample names and
            contrasts, if available.

    Returns:
        dict: Dict containing all plots, one for each key.
    """
    assigned = bar(
        tax_data["sample n reads"],
        x="index",
        y="value",
        color="variable",
        labels={
            "value": "% of reads",
            "index": "Sample name",
            "variable": "Category",
        },
        template="plotly_white",
    )
    write_table(tax_data["sample n reads"], output_path, "classified_reads.tsv")

    assigned.update_layout(
        xaxis={"categoryorder": "category ascending"},
    )

    assigned_html = export_to_html(assigned, "assigned-plot")

    # Beta diversity plots
    plot_beta_div = False if tax_data["beta div"] is None else True

    if plot_beta_div:
        pcoa_embed = (
            tax_data["beta div"]
            .samples[["PC1", "PC2"]]
            .rename_axis("sample")
            .reset_index()
        )
        var_explained = (
            tax_data["beta div"]
            .proportion_explained[:9]
            .to_frame(name="Variance Explained")
            .reset_index()
            .rename(columns={"index": "PC"})
        )

        write_table(var_explained, output_path, "pcoa_variance_explained.tsv")

        pcoa_var = line(
            var_explained,
            x="PC",
            y="Variance Explained",
            text="PC",
            template="plotly_white",
        )
        pcoa_var.update_traces(textposition="bottom right")

    # TODO: Improve this check
    if contrast_df is not None and "group" in contrast_df.columns:
        contrast_df["sample"] = [
            str(Path(s).name) for s in contrast_df["sample"].to_list()
        ]
        merged_taxas_df = merge_with_contrasts(tax_data["common taxas"], contrast_df)

        common_taxas = plot_common_taxas(
            merged_taxas_df, output_path, facet_col="group"
        )
        common_taxas.update_xaxes(matches=None)

        abund_div = plot_abund_div(
            merge_with_contrasts(tax_data["abund and div"], contrast_df),
            output_path,
            color="group",
        )
        if plot_beta_div:
            betadiv_pcoa = plot_beta_pcoa(
                merge_with_contrasts(pcoa_embed, contrast_df, left_colname="sample"),
                output_path,
                color="group",
            )

    else:
        common_taxas = plot_common_taxas(tax_data["common taxas"], output_path)

        abund_div = plot_abund_div(tax_data["abund and div"], output_path)
        if plot_beta_div:
            betadiv_pcoa = plot_beta_pcoa(pcoa_embed, output_path)

    common_taxas.update_traces(showlegend=False)
    common_taxas.update_layout(
        xaxis={"categoryorder": "category ascending"},
    )

    return_dict = {
        "assigned_plot": assigned_html,
        "common_taxas_plot": export_to_html(common_taxas, "taxas-plot"),
        "abund_div_plot": export_to_html(abund_div, "abund-div-plot"),
    }

    if plot_beta_div:
        return_dict["pcoa_var_plot"] = export_to_html(
            pcoa_var, "pcoa-explained-variance"
        )
        return_dict["beta_div_pcoa"] = export_to_html(betadiv_pcoa, "betadiv_pcoa")

    return return_dict

merge_with_contrasts(df, contrast_df, left_colname='index')

Merges a dataframe with the dataframe containing contrasts (or groups)

Source code in microview/plotting.py
43
44
45
46
47
48
49
50
51
def merge_with_contrasts(df, contrast_df, left_colname: Optional[str] = "index"):
    """
    Merges a dataframe with the dataframe containing contrasts (or groups)
    """
    merged_df = df.merge(
        contrast_df, left_on=left_colname, right_on="sample", how="left"
    )

    return merged_df

plot_abund_div(abund_div_df, output_path, **kwargs)

Generate scatter plot of Pielou's Evenness and Shannon's Diversity (alpha)

Source code in microview/plotting.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def plot_abund_div(abund_div_df, output_path, **kwargs):
    """
    Generate scatter plot of Pielou's Evenness and Shannon's Diversity (alpha)
    """
    write_table(abund_div_df, output_path, "abund_diversity.tsv")

    return scatter(
        abund_div_df,
        x="Pielou Evenness",
        y="Shannon Diversity",
        size="N Taxas",
        hover_data=["index"],
        labels={"N Taxas": "# taxas"},
        template="plotly_white",
        color_discrete_sequence=colors.qualitative.Safe[3:],
        **kwargs,
    )

plot_beta_pcoa(beta_pcoa, output_path, **kwargs)

Generate scatter plot of two first coordinates of Beta Diversity PCoA

Source code in microview/plotting.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def plot_beta_pcoa(beta_pcoa, output_path, **kwargs):
    """
    Generate scatter plot of two first coordinates of Beta Diversity PCoA
    """
    write_table(beta_pcoa, output_path, "beta_pcoa.tsv")

    fig = scatter(
        beta_pcoa,
        x="PC1",
        y="PC2",
        hover_data=["sample"],
        labels={"sample": "Sample name"},
        template="plotly_white",
        **kwargs,
    )
    fig.update_traces(marker_size=10)
    return fig

plot_common_taxas(common_taxas_df, output_path, **kwargs)

Generate bar plot with most common taxas

Source code in microview/plotting.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def plot_common_taxas(common_taxas_df, output_path, **kwargs):
    """
    Generate bar plot with most common taxas
    """
    write_table(common_taxas_df, output_path, "common_taxas.tsv")

    return bar(
        common_taxas_df.sort_values(by=["value", "variable"], ascending=[False, True]),
        x="index",
        y="value",
        color="variable",
        labels={
            "index": "Sample name",
            "value": "% of reads",
            "variable": "Taxon name",
        },
        template="plotly_white",
        color_discrete_sequence=colors.qualitative.Alphabet,
        **kwargs,
    )

write_table(df, output_path, path)

Write a dataframe to a file

Source code in microview/plotting.py
32
33
34
35
36
37
38
39
40
def write_table(df, output_path, path):
    """
    Write a dataframe to a file
    """
    dirpath = Path(output_path).parent.resolve() / Path("microview_tables")
    Path(dirpath).mkdir(exist_ok=True)
    path = dirpath / path

    df.to_csv(path, sep="\t", index=False)