customgraphics.py 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. """ Custom graphics lib for pop gen or genomics
  2. FOREST Thomas (thomas.forest@college-de-france.fr)
  3. """
  4. import matplotlib.pyplot as plt
  5. import matplotlib.ticker as ticker
  6. import numpy as np
  7. import gc
  8. import time
  9. import datetime
  10. import pandas as pd
  11. # custom libs
  12. from frst import vcf_utils
  13. def heatmap(data, row_labels=None, col_labels=None, ax=None,
  14. cbar_kw={}, cbarlabel="", **kwargs):
  15. """
  16. Create a heatmap from a numpy array and two lists of labels.
  17. (from the matplotlib doc)
  18. Parameters
  19. ----------
  20. data
  21. A 2D numpy array of shape (M, N).
  22. row_labels
  23. A list or array of length M with the labels for the rows.
  24. col_labels
  25. A list or array of length N with the labels for the columns.
  26. ax
  27. A `matplotlib.axes.Axes` instance to which the heatmap is plotted. If
  28. not provided, use current axes or create a new one. Optional.
  29. cbar_kw
  30. A dictionary with arguments to `matplotlib.Figure.colorbar`. Optional.
  31. cbarlabel
  32. The label for the colorbar. Optional.
  33. **kwargs
  34. All other arguments are forwarded to `imshow`.
  35. """
  36. if not ax:
  37. ax = plt.gca()
  38. # Plot the heatmap
  39. im = ax.imshow(data, **kwargs)
  40. # Create colorbar
  41. cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)
  42. cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
  43. # Show all ticks and label them with the respective list entries.
  44. if col_labels:
  45. ax.set_xticks(col_labels)
  46. if row_labels:
  47. ax.set_yticks(row_labels)
  48. # Let the horizontal axes labeling appear on top.
  49. ax.tick_params(top=True, bottom=False,
  50. labeltop=True, labelbottom=False)
  51. # Rotate the tick labels and set their alignment.
  52. plt.setp(ax.get_xticklabels(), rotation=-30, ha="right",
  53. rotation_mode="anchor")
  54. # Turn spines off and create white grid.
  55. ax.spines[:].set_visible(False)
  56. ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)
  57. ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)
  58. ax.grid(which="minor", color="w", linestyle='-', linewidth=3)
  59. ax.tick_params(which="minor", bottom=False, left=False)
  60. return im, cbar
  61. def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
  62. textcolors=("black", "white"),
  63. threshold=None, **textkw):
  64. """
  65. A function to annotate a heatmap.
  66. (from the matplotlib doc)
  67. Parameters
  68. ----------
  69. im
  70. The AxesImage to be labeled.
  71. data
  72. Data used to annotate. If None, the image's data is used. Optional.
  73. valfmt
  74. The format of the annotations inside the heatmap. This should either
  75. use the string format method, e.g. "$ {x:.2f}", or be a
  76. `matplotlib.ticker.Formatter`. Optional.
  77. textcolors
  78. A pair of colors. The first is used for values below a threshold,
  79. the second for those above. Optional.
  80. threshold
  81. Value in data units according to which the colors from textcolors are
  82. applied. If None (the default) uses the middle of the colormap as
  83. separation. Optional.
  84. **kwargs
  85. All other arguments are forwarded to each call to `text` used to create
  86. the text labels.
  87. """
  88. if not isinstance(data, (list, np.ndarray)):
  89. data = im.get_array()
  90. # Normalize the threshold to the images color range.
  91. if threshold is not None:
  92. threshold = im.norm(threshold)
  93. else:
  94. threshold = im.norm(data.max())/2.
  95. # Set default alignment to center, but allow it to be
  96. # overwritten by textkw.
  97. kw = dict(horizontalalignment="center",
  98. verticalalignment="center")
  99. kw.update(textkw)
  100. # Get the formatter in case a string is supplied
  101. if isinstance(valfmt, str):
  102. valfmt = ticker.StrMethodFormatter(valfmt)
  103. # Loop over the data and create a `Text` for each "pixel".
  104. # Change the text's color depending on the data.
  105. texts = []
  106. for i in range(data.shape[0]):
  107. for j in range(data.shape[1]):
  108. kw.update(color=textcolors[int(im.norm(data[i, j]) > threshold)])
  109. text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)
  110. texts.append(text)
  111. return texts
  112. def plot_matrix(mat, legend=None, color_scale_type="YlGn", cbarlabel = "qt", title=None):
  113. fig, ax = plt.subplots(figsize=(10,8))
  114. if legend:
  115. row_labels = [k for k in range(len(mat))]
  116. col_labels = [k for k in range(len(mat[0]))]
  117. im, cbar = heatmap(mat, row_labels, col_labels, ax=ax,
  118. cmap=color_scale_type, cbarlabel=cbarlabel)
  119. else:
  120. im, cbar = heatmap(mat, ax=ax,
  121. cmap=color_scale_type, cbarlabel=cbarlabel)
  122. #texts = annotate_heatmap(im, valfmt="{x:.5f}")
  123. if title:
  124. ax.set_title(title)
  125. fig.tight_layout()
  126. plt.show()
  127. def plot(x, y, outfile = None, outfolder = None, ylab=None, xlab=None,
  128. title=None, label = None, show=True):
  129. if x:
  130. fig, = plt.plot(x, y)
  131. else:
  132. # x is optional
  133. fig, = plt.plot(y)
  134. if label:
  135. # if legend
  136. fig.set_label(label)
  137. plt.legend()
  138. if ylab:
  139. plt.ylabel(ylab)
  140. if xlab:
  141. plt.xlabel(xlab)
  142. if title:
  143. plt.title(title)
  144. if outfile:
  145. plt.savefig(outfile)
  146. else:
  147. if show == True:
  148. plt.show()
  149. def scatter(x, y, ylab=None, xlab=None, title=None):
  150. plt.scatter(x, y)
  151. if ylab:
  152. plt.ylabel(ylab)
  153. if xlab:
  154. plt.xlabel(xlab)
  155. if title:
  156. plt.title(title)
  157. plt.show()
  158. def barplot(x, y, ylab=None, xlab=None, title=None):
  159. plt.bar(x, y)
  160. if ylab:
  161. plt.ylabel(ylab)
  162. if xlab:
  163. plt.xlabel(xlab)
  164. if title:
  165. plt.title(title)
  166. plt.show()
  167. def plot_chrom_continuity(vcf_entries, chr_id, x=None, y=None, outfile = None,
  168. outfolder = None, returned=False, show=True, label=True):
  169. chr_name = list(vcf_entries.keys())[chr_id]
  170. if label:
  171. label = chr_name
  172. chr_entries = vcf_entries[chr_name]
  173. genotyped_pos = vcf_utils.genotyping_continuity_plot(chr_entries)
  174. if returned:
  175. # if we do not want to plot while executing
  176. # useful for storing the x,y coords in a variable for ex.
  177. return genotyped_pos
  178. else:
  179. # to plot on the fly
  180. plot(x, y=genotyped_pos[1], ylab = "genotyped pos.",
  181. xlab = "pos. in ref.",
  182. title = "Genotyped pos in chr "+str(chr_id+1)+":'"+chr_name+"'",
  183. outfile = outfile, outfolder = outfolder, show=show, label=label)
  184. def plot_whole_karyotype(recent_variants, mem_clean = False):
  185. coords = []
  186. for chr in range(len(recent_variants)):
  187. x, y = vcf_utils.customgraphics.plot_chrom_continuity(recent_variants, chr_id = chr, show = False, returned = True)
  188. coords.append([x, y])
  189. if mem_clean:
  190. start = time.time()
  191. del x
  192. del y
  193. gc.collect()
  194. end = time.time()
  195. print("Cleaned mem. in", str(datetime.timedelta(seconds=end - start)))
  196. # maybe add a clean of recent_variants in extreme cases, before building the plots
  197. return coords
  198. def plot_chrom_coverage(vcf_entries, chr_id):
  199. chr_name = list(vcf_entries.keys())[chr_id]
  200. chr_entries = vcf_entries[chr_name]
  201. coverage = vcf_utils.compute_coverage(chr_entries)
  202. barplot(coverage[0], coverage[1], ylab = "coverage (X)",
  203. xlab = "pos. in ref.",
  204. title = "Coverage for chr "+str(chr_id+1)+":'"+chr_name+"'")