customgraphics.py 6.2KB

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