Skip to content

Commit b5bbc88

Browse files
committed
DiffuPath views statistical test fdr_barchart added and general refactor and cleaning
1 parent 4080783 commit b5bbc88

2 files changed

Lines changed: 151 additions & 106 deletions

File tree

requirements-rtd.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,9 @@ chart_studio==1.0.0
1313
matplotlib_venn==0.11.5
1414
bio2bel==0.2.1
1515
pathme
16+
openpyxl
1617
diffupy
1718
sphinx
1819
sphinx-rtd-theme
1920
sphinx-click
20-
sphinx-autodoc-typehints
21+
sphinx-autodoc-typehints

src/diffupath/views.py

Lines changed: 149 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,163 @@
22

33
"""Visualization methods."""
44

5-
import chart_studio.plotly as py
65
import matplotlib
76
import matplotlib.pyplot as plt
87
import numpy as np
9-
import plotly.graph_objs as go
8+
9+
from diffupath.cross_validation import get_normalized_p_values
10+
1011
from matplotlib_venn import venn3
1112

1213

13-
def heatmap(
14-
data, row_labels, col_labels, ax=None, cbar_kw=None, cbarlabel="", title="", **kwargs
14+
def show_box_plot(
15+
data_dict,
16+
x_label='',
17+
y_label='',
18+
color_palette=None
1519
):
16-
"""Create a heatmap from a numpy array and two lists of labels.
20+
"""Plot boxplot."""
21+
if color_palette is None:
22+
color_palette = ['royalblue', 'forestgreen', 'khaki', 'lightcoral', 'yellow', 'green']
23+
24+
bplots = []
25+
26+
fig, axs = plt.subplots(nrows=1,
27+
ncols=len(data_dict),
28+
figsize=(18, 6)
29+
)
30+
if not isinstance(axs, np.ndarray):
31+
axs = [axs]
32+
33+
for i, (dataset_label, dataset) in enumerate(data_dict.items()):
34+
# rectangular box plot
35+
bplot = axs[i].boxplot(list(dataset.values()),
36+
vert=True, # vertical box alignment
37+
patch_artist=True, # fill with color
38+
labels=list(dataset.keys())
39+
) # will be used to label x-ticks
40+
axs[i].set_title(dataset_label)
41+
42+
bplots.append(bplot)
43+
44+
# fill with colors
45+
for bplot in bplots:
46+
for i, (patch, color) in enumerate(zip(bplot['boxes'], color_palette)):
47+
patch.set_facecolor(color_palette[i])
48+
49+
# adding horizontal grid lines
50+
for i, ax in enumerate(axs):
51+
ax.yaxis.grid(True)
52+
ax.set_xlabel(x_label)
53+
ax.set_ylabel(y_label)
1754

18-
Optional parameters: ax: A matplotlib.axes.Axes instance to which the heatmap is plotted. If not provided, use
19-
current axes or create a new one. cbar_kw: A dictionary with arguments to :meth:`matplotlib.Figure.colorbar`.
20-
cbarlabel: The label for the colorbar.
21-
22-
:param data: A 2D numpy array of shape (N,M)
23-
:param row_labels: A list or array of length N with the labels for the rows
24-
:param col_labels: A list or array of length N with the labels for the columns
25-
:param ax: axis
26-
:param cbar_kw: kwars for cbar
27-
:param cbarlabel: label
28-
:param title: title
29-
"""
55+
plt.show()
56+
57+
58+
def fdr_barchart_three_plot(
59+
metrics,
60+
p_values_func,
61+
title='Statistic Test',
62+
legend=None
63+
):
64+
if legend is None:
65+
if isinstance(metrics, dict):
66+
legend = list(metrics.keys())
67+
else:
68+
legend = ('Dataset 1', 'Dataset 2', 'Dataset 3')
69+
70+
if isinstance(metrics, dict):
71+
metrics = list(metrics.values())
72+
73+
plt.rcParams.update({'font.size': 17})
74+
75+
normalized_p_values = []
76+
77+
for metric in metrics:
78+
p_values = p_values_func(metric)
79+
normalized_p_values.append(list(get_normalized_p_values(p_values).values()))
80+
x = list(p_values.keys())
81+
82+
ind = np.arange(len(x)) # the x locations for the groups
83+
width = 0.27 # the width of the bars
84+
85+
fig = plt.figure()
86+
ax = fig.add_subplot(111)
87+
88+
fig.set_size_inches(14.5, 7.5)
89+
90+
rects1 = ax.bar(ind, normalized_p_values[0], width, color='forestgreen')
91+
rects2 = ax.bar(ind + width, normalized_p_values[1], width, color='tomato')
92+
rects3 = ax.bar(ind + width * 2, normalized_p_values[2], width, color='steelblue')
93+
94+
ax.set_ylabel("normalized FDR -log10(p-value)")
95+
plt.xlabel(title)
96+
97+
ax.set_xticks(ind + width)
98+
ax.set_xticklabels(x, ha='left', rotation=-45)
99+
ax.legend((rects1[0], rects2[0], rects3[0]), legend)
100+
101+
ax.plot([-0.2, 6], [-np.math.log10(0.05), -np.math.log10(0.05)], "k--")
102+
103+
plt.show()
104+
105+
106+
def show_venn_diagram(
107+
intersections,
108+
set_labels=('KEGG', 'Reactome', 'WikiPathways')
109+
):
110+
"""Show venn diagram."""
111+
intersections_len = [len(intersection) for name, intersection in intersections.items()]
112+
113+
plt.figure(figsize=(17, 8))
114+
v = venn3(subsets=intersections_len, set_labels=set_labels)
115+
116+
plt.show()
30117

118+
119+
def show_heatmap(
120+
entity_number,
121+
entity_count,
122+
databases,
123+
entity_types,
124+
title="DiffuPath Mapping"
125+
):
126+
fig, ax = plt.subplots(figsize=(15, 7))
127+
128+
im, cbar = _generate_heatmap(entity_number, databases, entity_types, ax=ax,
129+
cmap="YlGn", cbarlabel="percentage [0-1]")
130+
_ = _annotate_heatmap(im, entity_count=entity_count, valfmt="{x:1} ")
131+
132+
fig.tight_layout()
133+
ax.set_title(title)
134+
135+
plt.show()
136+
137+
138+
def _generate_heatmap(
139+
data,
140+
row_labels,
141+
col_labels,
142+
ax=None,
143+
cbar_kw={},
144+
cbarlabel="",
145+
title="",
146+
**kwargs
147+
):
148+
"""Create a heatmap from a numpy array and two lists of labels.
149+
150+
Optional parameters: ax: A matplotlib.axes.Axes instance to which the heatmap is plotted. If not provided, use
151+
current axes or create a new one. cbar_kw: A dictionary with arguments to :meth:`matplotlib.Figure.colorbar`.
152+
cbarlabel: The label for the colorbar.
153+
154+
:param data: A 2D numpy array of shape (N,M)
155+
:param row_labels: A list or array of length N with the labels for the rows
156+
:param col_labels: A list or array of length N with the labels for the columns
157+
:param ax: axis
158+
:param cbar_kw: kwars for cbar
159+
:param cbarlabel: label
160+
:param title: title
161+
"""
31162
if not ax:
32163
ax = plt.gca()
33164

@@ -67,7 +198,7 @@ def heatmap(
67198
return im, cbar
68199

69200

70-
def annotate_heatmap(
201+
def _annotate_heatmap(
71202
im,
72203
data=None,
73204
valfmt="{x:.2f}",
@@ -114,90 +245,3 @@ def annotate_heatmap(
114245
texts.append(text)
115246

116247
return texts
117-
118-
119-
def show_heatmap(count, percentage, databases, entity_types):
120-
"""Show heatmap"""
121-
fig, ax = plt.subplots(figsize=(15, 7))
122-
123-
im, cbar = heatmap(percentage, databases, entity_types, ax=ax,
124-
cmap="YlGn", cbarlabel="percentage [0-1]")
125-
texts = annotate_heatmap(im, entity_count=count, valfmt="{x:1} ")
126-
127-
fig.tight_layout()
128-
ax.set_title("Dataset 1 DiffuPath Mapping")
129-
130-
plt.show()
131-
132-
133-
def box_plot_from_dict(d, title='Box plot', x_title='x', y_title='y'):
134-
"""Plot boxplot."""
135-
data = [go.Box(
136-
y=v,
137-
name=k
138-
) for k, v in d.items()
139-
]
140-
141-
layout = go.Layout(
142-
title=go.layout.Title(
143-
text=title,
144-
xref='paper'
145-
),
146-
xaxis=go.layout.XAxis(
147-
title=go.layout.xaxis.Title(
148-
text=x_title
149-
)
150-
),
151-
yaxis=go.layout.YAxis(
152-
title=go.layout.yaxis.Title(
153-
text=y_title
154-
)
155-
)
156-
)
157-
158-
fig = go.Figure(data=data, layout=layout)
159-
160-
return py.iplot(fig)
161-
162-
163-
def box_plot_from_two_dimension_dict(d, y_label='y'):
164-
"""Boxplot two dimensions."""
165-
x = [k2 for k1, v1 in d.items() for k2, v2 in v1.items() for i in range(len(v2))]
166-
167-
color_palete = ['#FF4136', '#3d9970', '#344f9e', '#bfc464']
168-
color_dict = {}
169-
i = 0
170-
171-
for k, v in d.items():
172-
color_dict[k] = color_palete[i]
173-
i += 1
174-
175-
data = [go.Box(
176-
y=[i for k2, v2 in v1.items() for i in v2],
177-
x=x,
178-
name=k1,
179-
marker=dict(
180-
color=color_dict[k1]
181-
)
182-
) for k1, v1 in d.items()]
183-
184-
layout = go.Layout(
185-
yaxis=dict(
186-
title=y_label,
187-
zeroline=False
188-
),
189-
boxmode='group'
190-
)
191-
fig = go.Figure(data=data, layout=layout)
192-
193-
return py.iplot(fig)
194-
195-
196-
def show_venn_diagram(intersections, set_labels=('KEGG', 'Reactome', 'WikiPathways')):
197-
"""Show venn diagram."""
198-
intersections_len = [len(intersection) for name, intersection in intersections.items()]
199-
200-
plt.figure(figsize=(17, 8))
201-
v = venn3(subsets=intersections_len, set_labels=set_labels)
202-
203-
plt.show()

0 commit comments

Comments
 (0)