Commit ccd2678b authored by nfontrod's avatar nfontrod
Browse files

src/visu/figure_maker.py: change style of the figure + add parameter ylim

parent 7f77571e
Pipeline #146 passed with stages
in 1 minute and 12 seconds
...@@ -7,7 +7,7 @@ Description: ...@@ -7,7 +7,7 @@ Description:
""" """
from pathlib import Path from pathlib import Path
from typing import List, Union, Any, Tuple from typing import List, Union, Any, Tuple, Optional
from doctest import testmod from doctest import testmod
from ..bed_handler.config import TestConfig from ..bed_handler.config import TestConfig
import pandas as pd import pandas as pd
...@@ -16,6 +16,8 @@ import seaborn as sns ...@@ -16,6 +16,8 @@ import seaborn as sns
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from tqdm import tqdm from tqdm import tqdm
from loguru import logger from loguru import logger
import matplotlib as mpl
import matplotlib.font_manager
def load_bed(bed: Path, bed_name: str) -> List[List[Union[int, str]]]: def load_bed(bed: Path, bed_name: str) -> List[List[Union[int, str]]]:
...@@ -292,7 +294,7 @@ def figure_metagene(df_sum: pd.DataFrame, show_replicate: bool, ...@@ -292,7 +294,7 @@ def figure_metagene(df_sum: pd.DataFrame, show_replicate: bool,
border_names: List[str], nb_bin: int, border_names: List[str], nb_bin: int,
environment: List[int], bed_name: str, environment: List[int], bed_name: str,
output: Path, norm: Union[int, Path], output: Path, norm: Union[int, Path],
condition_col: str) -> None: condition_col: str, ylim: Optional[List[float]]) -> None:
""" """
Create a metagene figure on the region of interest. Create a metagene figure on the region of interest.
...@@ -309,8 +311,15 @@ def figure_metagene(df_sum: pd.DataFrame, show_replicate: bool, ...@@ -309,8 +311,15 @@ def figure_metagene(df_sum: pd.DataFrame, show_replicate: bool,
the samples or a file containing the normalisations to apply to \ the samples or a file containing the normalisations to apply to \
each samples each samples
:param condition_col: The name of the condition columns :param condition_col: The name of the condition columns
:param ylim: The range of the y axis
""" """
sns.set(context='poster', style='white') font_files = matplotlib.font_manager.findSystemFonts(fontpaths=None,
fontext='ttf')
font_list = matplotlib.font_manager.createFontList(font_files)
matplotlib.font_manager.fontManager.ttflist.extend(font_list)
sns.set(context='poster', style='white', font_scale=1.4)
mpl.rcParams['font.family'] = 'Arial'
if show_replicate: if show_replicate:
g = sns.relplot('bin', 'coverage', hue=condition_col, data=df_sum, g = sns.relplot('bin', 'coverage', hue=condition_col, data=df_sum,
kind='line', style='replicate', ci=None, kind='line', style='replicate', ci=None,
...@@ -332,8 +341,8 @@ def figure_metagene(df_sum: pd.DataFrame, show_replicate: bool, ...@@ -332,8 +341,8 @@ def figure_metagene(df_sum: pd.DataFrame, show_replicate: bool,
tmp_bed_name = bed_name.replace("--", ", ") tmp_bed_name = bed_name.replace("--", ", ")
title = f"Average coverage in region '{tmp_bed_name}'" title = f"Average coverage in region '{tmp_bed_name}'"
if environment[0] != 0: if environment[0] != 0:
title += f"\nand in their surrounding regions of {environment[0]} nt" title += f" and in their surrounding regions of {environment[0]} nt"
g.fig.suptitle(title) g.fig.suptitle(title, fontsize=30)
tmp_bed_name = bed_name.replace("--", "-") tmp_bed_name = bed_name.replace("--", "-")
outfile_title = f"metagene_{tmp_bed_name}_{nb_bin}bin_" \ outfile_title = f"metagene_{tmp_bed_name}_{nb_bin}bin_" \
f"{environment[0]}_nt-around-{environment[1]}-bin" f"{environment[0]}_nt-around-{environment[1]}-bin"
...@@ -342,6 +351,9 @@ def figure_metagene(df_sum: pd.DataFrame, show_replicate: bool, ...@@ -342,6 +351,9 @@ def figure_metagene(df_sum: pd.DataFrame, show_replicate: bool,
elif isinstance(norm, Path): elif isinstance(norm, Path):
outfile_title += f"_file_norm" outfile_title += f"_file_norm"
outfile_title += ".pdf" outfile_title += ".pdf"
if ylim[0] is not None:
g.ax.set_ylim(ylim[0], ylim[1])
g.ax.tick_params(left=True, bottom=True)
g.savefig(output / outfile_title) g.savefig(output / outfile_title)
g.fig.clf() g.fig.clf()
...@@ -438,7 +450,8 @@ def create_figure(design: Path, bw_folder: Path, region_beds: List[Path], ...@@ -438,7 +450,8 @@ def create_figure(design: Path, bw_folder: Path, region_beds: List[Path],
norm: Union[int, Path, None] = None, norm: Union[int, Path, None] = None,
show_replicate: bool = True, environment: List[int] = (0, 0), show_replicate: bool = True, environment: List[int] = (0, 0),
border_names: List[str] = ('', ''), border_names: List[str] = ('', ''),
output: Path = Path('.')) -> None: output: Path = Path('.'),
ylim: List[float] = (None, None)) -> None:
""" """
Create A metagene or a barplot figure from bigwig file on regions defined \ Create A metagene or a barplot figure from bigwig file on regions defined \
in the bed file provided with 'region_bed' parameter. in the bed file provided with 'region_bed' parameter.
...@@ -464,14 +477,14 @@ def create_figure(design: Path, bw_folder: Path, region_beds: List[Path], ...@@ -464,14 +477,14 @@ def create_figure(design: Path, bw_folder: Path, region_beds: List[Path],
the number of bin used to represent those surrounding regions. the number of bin used to represent those surrounding regions.
:param border_names: The name of the borders :param border_names: The name of the borders
:param output: Folder where the results will be created :param output: Folder where the results will be created
:param ylim: The range of y-axis
""" """
if len(region_beds) != len(bed_names): if len(region_beds) != len(bed_names):
raise IndexError("Parameter region_beds and bed_names should " raise IndexError("Parameter region_beds and bed_names should "
"have the same length") "have the same length")
df_exp = pd.read_csv(design, sep="\t") df_exp = pd.read_csv(design, sep="\t")
regions = load_beds(region_beds, bed_names) regions = load_beds(region_beds, bed_names)
region_bed_name = "-".join([b.name.replace('.bed', '') region_bed_name = "-".join(b.name.replace('.bed', '') for b in region_beds)
for b in region_beds])
outfile = f'tmp_cov_table_{design.name.replace(".txt", "")}' \ outfile = f'tmp_cov_table_{design.name.replace(".txt", "")}' \
f'_{region_bed_name}_{nb_bin}bin_' \ f'_{region_bed_name}_{nb_bin}bin_' \
f'{environment[0]}_nt-around-{environment[1]}-bin' f'{environment[0]}_nt-around-{environment[1]}-bin'
...@@ -495,7 +508,8 @@ def create_figure(design: Path, bw_folder: Path, region_beds: List[Path], ...@@ -495,7 +508,8 @@ def create_figure(design: Path, bw_folder: Path, region_beds: List[Path],
ordered_condition, bed_names) ordered_condition, bed_names)
if figure_type == "metagene": if figure_type == "metagene":
figure_metagene(df_sum, show_replicate, border_names, nb_bin, figure_metagene(df_sum, show_replicate, border_names, nb_bin,
environment, region_kind, output, norm, cond_col) environment, region_kind, output, norm, cond_col,
ylim)
else: else:
if 'location' in df_sum.columns: if 'location' in df_sum.columns:
for cur_region in df_sum['location'].unique(): for cur_region in df_sum['location'].unique():
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment