Skip to content

Plotting

Miscellaneous functions for plotting DFEs.

plot_biv_dfe(gammax, gammay, sel_dist, params, logweight=True, ax=None, xlabel='$\\gamma_1$', ylabel='$\\gamma_2$', cmap='gray_r', colorbar=True, vmin=0, clip_on=True)

Plot a bivariate DFE (for negative gammas).

Parameters:

Name Type Description Default
gammax array - like

Grids of gamma values to plot with. Non-negative values are discarded.

required
gammay array - like

Grids of gamma values to plot with. Non-negative values are discarded.

required
sel_dist callable

Bivariate probability distribution, taking arguments (xx, yy, params).

required
params array - like

Parameters for sel_dist.

required
logweight bool

If True, plotted values are weighted by x and y, so that the total probability within each cell is plotted rather than the probability density. Defaults to True.

True
ax Axes

Matplotlib axes to plot into. If None, plt.gca() is used. Defaults to None.

None
xlabel str

Labels for x and y axes. Defaults to '$\gamma_1$'.

'$\\gamma_1$'
ylabel str

Labels for x and y axes. Defaults to '$\gamma_2$'.

'$\\gamma_2$'
cmap str

Colormap to plot with. Defaults to 'gray_r'.

'gray_r'
colorbar bool

If True, include a colorbar alongside the plot. Defaults to True.

True
vmin float

Values below this will be colored white. Defaults to 0.

0
clip_on bool

If False, plot will extend outside of axes. Defaults to True.

True

Returns:

Name Type Description
ax Axes

The axes with the plot.

Note

See https://matplotlib.org/2.0.2/users/colormaps.html for colormap tips.

Source code in dadi/DFE/Plotting.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def plot_biv_dfe(gammax, gammay, sel_dist, params, logweight=True, ax=None,
                 xlabel='$\gamma_1$', ylabel='$\gamma_2$', cmap='gray_r',
                 colorbar=True, vmin=0, clip_on=True):
    """
    Plot a bivariate DFE (for negative gammas).

    Parameters:
        gammax (array-like): Grids of gamma values to plot with. 
            Non-negative values are discarded.
        gammay (array-like): Grids of gamma values to plot with. 
            Non-negative values are discarded.
        sel_dist (callable): Bivariate probability distribution, taking 
            arguments (xx, yy, params).
        params (array-like): Parameters for sel_dist.
        logweight (bool, optional): If True, plotted values are weighted by x 
            and y, so that the total probability within each cell is plotted 
            rather than the probability density. Defaults to True.
        ax (matplotlib.axes.Axes, optional): Matplotlib axes to plot into. 
            If None, plt.gca() is used. Defaults to None.
        xlabel (str, optional): Labels for x and y axes. Defaults to 
            '$\gamma_1$'.
        ylabel (str, optional): Labels for x and y axes. Defaults to 
            '$\gamma_2$'.
        cmap (str, optional): Colormap to plot with. Defaults to 'gray_r'.
        colorbar (bool, optional): If True, include a colorbar alongside the 
            plot. Defaults to True.
        vmin (float, optional): Values below this will be colored white. 
            Defaults to 0.
        clip_on (bool, optional): If False, plot will extend outside of axes. 
            Defaults to True.

    Returns:
        ax (matplotlib.axes.Axes): The axes with the plot.

    Note:
        See https://matplotlib.org/2.0.2/users/colormaps.html for colormap tips.
    """
    # Discard non-negative values of gamma.
    gammax = gammax[gammax < 0]
    gammay = gammay[gammay < 0]

    # Midpoints of each gamma bin (on a log-scale)
    xmid = np.sqrt(gammax[:-1] * gammax[1:])
    ymid = np.sqrt(gammay[:-1] * gammay[1:])
    # Calculate weights
    weights = sel_dist(xmid, ymid, params)
    # Convert from probability density to probability value within each cell.
    if logweight:
        weights *= xmid[:,np.newaxis] * ymid[np.newaxis,:]

    # Plot data
    X,Y = np.meshgrid(gammax, gammay)

    if not ax:
        # Hiding import here, so Selection_2d.py isn't dependent on matplotlib.
        import matplotlib.pyplot as plt
        ax = plt.gca()
    masked = np.ma.masked_where(weights.T<vmin,weights.T)
    mappable = ax.pcolor(X,Y,masked, cmap=cmap, vmin=vmin, clip_on=clip_on)

    # Plot the colorbar, labeling carefully depending on logweight
    if colorbar:
        cb = ax.get_figure().colorbar(mappable)
        if logweight:
            cb.set_label('Probability')
        else:
            cb.set_label('Probability density')

    # Set to logscale. Use symlog because it handles negative values cleanly
    ax.set_xscale('symlog', linthresh=abs(gammax).min())
    ax.set_yscale('symlog', linthresh=abs(gammay).min())

    ax.set_xlabel(xlabel, fontsize='large')
    ax.set_ylabel(ylabel, fontsize='large')

    return ax

plot_biv_point_pos_dfe(gammax, gammay, sel_dist, params, rho=0, logweight=True, xlabel='$\\gamma_1$', ylabel='$\\gamma_2$', cmap='gray_r', fignum=None, colorbar=True, vmin=0)

Plot a bivariate DFE (for negative gammas) with a positive point mass.

Parameters:

Name Type Description Default
gammax array - like

Grids of gamma values to plot with. Non-negative values are discarded.

required
gammay array - like

Grids of gamma values to plot with. Non-negative values are discarded.

required
sel_dist callable

Bivariate probability distribution, taking arguments (xx, yy, params).

required
params array - like

Parameters for sel_dist and positive selection. The last four parameters are assumed to be:

  • Proportion positive selection in pop1.

  • Positive gamma for pop1.

  • Proportion positive in pop2.

  • Positive gamma for pop2.

Earlier arguments are assumed to be for the continuous bivariate distribution.

required
rho float

Correlation coefficient used to connect negative and positive components of DFE. Defaults to 0.

0
logweight bool

If True, plotted values are weighted by x and y, so that the total probability within each cell is plotted rather than the probability density. Defaults to True.

True
xlabel str

Labels for x and y axes. Defaults to '$\gamma_1$'.

'$\\gamma_1$'
ylabel str

Labels for x and y axes. Defaults to '$\gamma_2$'.

'$\\gamma_2$'
cmap str

Colormap to plot with. Defaults to 'gray_r'.

'gray_r'
fignum int

Figure number to use. If None or the figure does not exist, a new one will be created. Defaults to None.

None
colorbar bool

If True, plot a scale bar for probability. Defaults to True.

True
vmin float

Values below this will be colored white. Defaults to 0.

0

Returns:

Name Type Description
fig Figure

The figure for the plot.

Notes
  • You might need to adjust subplot parameters using fig.subplots_adjust after plotting to see all labels, etc.

  • See https://matplotlib.org/2.0.2/users/colormaps.html for colormap tips.

Source code in dadi/DFE/Plotting.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def plot_biv_point_pos_dfe(gammax, gammay, sel_dist, params, rho=0,
                           logweight=True, xlabel='$\gamma_1$',
                           ylabel='$\gamma_2$', cmap='gray_r', fignum=None,
                           colorbar=True, vmin=0):
    """
    Plot a bivariate DFE (for negative gammas) with a positive point mass.

    Parameters:
        gammax (array-like): Grids of gamma values to plot with. 
            Non-negative values are discarded.
        gammay (array-like): Grids of gamma values to plot with. 
            Non-negative values are discarded.
        sel_dist (callable): Bivariate probability distribution, taking 
            arguments (xx, yy, params).
        params (array-like): Parameters for sel_dist and positive selection. 
            The last four parameters are assumed to be:

            - Proportion positive selection in pop1.

            - Positive gamma for pop1.

            - Proportion positive in pop2.

            - Positive gamma for pop2.

            Earlier arguments are assumed to be for the continuous bivariate 
            distribution.
        rho (float, optional): Correlation coefficient used to connect 
            negative and positive components of DFE. Defaults to 0.
        logweight (bool, optional): If True, plotted values are weighted by x 
            and y, so that the total probability within each cell is plotted 
            rather than the probability density. Defaults to True.
        xlabel (str, optional): Labels for x and y axes. Defaults to 
            '$\gamma_1$'.
        ylabel (str, optional): Labels for x and y axes. Defaults to 
            '$\gamma_2$'.
        cmap (str, optional): Colormap to plot with. Defaults to 'gray_r'.
        fignum (int, optional): Figure number to use. If None or the figure 
            does not exist, a new one will be created. Defaults to None.
        colorbar (bool, optional): If True, plot a scale bar for probability. 
            Defaults to True.
        vmin (float, optional): Values below this will be colored white. 
            Defaults to 0.

    Returns:
        fig (matplotlib.figure.Figure): The figure for the plot.

    Notes:
        - You might need to adjust subplot parameters using 
        `fig.subplots_adjust` after plotting to see all labels, etc.

        - See https://matplotlib.org/2.0.2/users/colormaps.html for colormap tips.
    """
    biv_params = params[:-4]
    ppos1, gammapos1, ppos2, gammapos2 = params[-4:]

    # Pull out negative gammas and calculate (log) midpoints.
    gammax = gammax[gammax < 0]
    gammay = gammay[gammay < 0]
    xmid = np.sqrt(gammax[:-1] * gammax[1:])
    ymid = np.sqrt(gammay[:-1] * gammay[1:])

    # Bivariate negative part of DFE
    neg_neg = sel_dist(xmid, ymid, biv_params)
    # Marginal DFEs from integrating along each axis
    neg_pos = np.trapz(neg_neg, ymid, axis=1)
    pos_neg = np.trapz(neg_neg, xmid, axis=0)

    if logweight:
        neg_neg *= xmid[:,np.newaxis] * ymid[np.newaxis,:]
        neg_pos *= xmid
        pos_neg *= ymid

    # Weighting factors for each quadrant of the DFE. Note that in the case
    # that ppos1==ppos2, these reduce to the model of Ragsdale et al. (2016)
    p_pos_pos = ppos1*ppos2 + rho*(np.sqrt(ppos1*ppos2) - ppos1*ppos2)
    p_pos_neg = (1-rho) * ppos1*(1-ppos2)
    p_neg_pos = (1-rho) * (1-ppos1)*ppos2
    p_neg_neg = (1-ppos1)*(1-ppos2)\
            + rho*(1-np.sqrt(ppos1*ppos2) - (1-ppos1)*(1-ppos2))

    # Apply weighting factors
    pos_neg *= p_pos_neg
    neg_pos *= p_neg_pos
    neg_neg *= p_neg_neg

    # For plotting, to put all on same color-scale.
    vmax = max([neg_neg.max(), neg_pos.max(), pos_neg.max(), p_pos_pos])

    # Grid points for plotting in positive selection regime.
    if gammapos1 != gammapos2:
        pos_grid = np.array(sorted([gammapos1, (gammapos1 + gammapos2)/2.,
                                    gammapos2]))
    else:
        pos_grid = np.array([gammapos1-1, gammapos1, gammapos1+1])

    # Fill in grids for plotting positive terms
    pos_neg_grid = np.zeros((3, len(ymid)))
    pos_neg_grid[pos_grid == gammapos1] = pos_neg
    neg_pos_grid = np.zeros((len(xmid), 3))
    neg_pos_grid[:,pos_grid == gammapos2] = neg_pos[:,np.newaxis]
    pos_pos_grid = np.zeros((3,3))
    pos_pos_grid[pos_grid == gammapos1, pos_grid == gammapos2] = p_pos_pos

    # For plotting with pcolor, need grid one size bigger.
    d = pos_grid[1] - pos_grid[0]
    plot_pos_grid = np.linspace(pos_grid[0] - d/2., pos_grid[-1] + d/2., 4)

    import matplotlib.pyplot as plt
    fig = plt.figure(num=fignum, figsize=(4,3), dpi=150)
    fig.clear()

    gs = plt.matplotlib.gridspec.GridSpec(2,3, width_ratios=[9,1,0.5],
                                          height_ratios=[1,9],
                                          wspace=0.15, hspace=0.15)
    # Create our four axes
    ax_ll = fig.add_subplot(gs[1,0])
    ax_ul = fig.add_subplot(gs[0,0], sharex=ax_ll)
    ax_lr = fig.add_subplot(gs[1,1], sharey=ax_ll)
    ax_ur = fig.add_subplot(gs[0,1], sharex=ax_lr, sharey=ax_ul)

    # Plot in each axis
    X,Y = np.meshgrid(gammax, gammay)
    masked = np.ma.masked_where(neg_neg.T<vmin,neg_neg.T)
    mappable = ax_ll.pcolor(X,Y,masked, cmap=cmap, vmin=vmin, vmax=vmax)
    X,Y = np.meshgrid(plot_pos_grid, plot_pos_grid)
    masked = np.ma.masked_where(pos_pos_grid.T<vmin,pos_pos_grid.T)
    ax_ur.pcolor(X,Y,masked, cmap=cmap, vmin=vmin, vmax=vmax)
    X,Y = np.meshgrid(plot_pos_grid, gammay)
    masked = np.ma.masked_where(pos_neg_grid.T<vmin,pos_neg_grid.T)
    ax_lr.pcolor(X,Y,masked, cmap=cmap, vmin=vmin, vmax=vmax)
    X,Y = np.meshgrid(gammax, plot_pos_grid)
    masked = np.ma.masked_where(neg_pos_grid.T<vmin,neg_pos_grid.T)
    ax_ul.pcolor(X,Y,masked, cmap=cmap, vmin=vmin, vmax=vmax)

    # Set logarithmic scale on legative parts
    ax_ll.set_xscale('symlog', linthresh=abs(gammax).min())
    ax_ll.set_yscale('symlog', linthresh=abs(gammay).min())

    # Remove interior axes lines and tickmarks
    ax_ll.spines['right'].set_visible(False)
    ax_ll.spines['top'].set_visible(False)
    ax_ll.tick_params('both', top=False, right=False, which='both')

    ax_ul.spines['right'].set_visible(False)
    ax_ul.spines['bottom'].set_visible(False)
    ax_ul.tick_params('both', top=True, bottom=False,
                      labelbottom=False, right=False, which='both')

    ax_lr.spines['left'].set_visible(False)
    ax_lr.spines['top'].set_visible(False)
    ax_lr.tick_params('both', right=True, left=False,
                      labelleft=False, top=False, which='both')

    ax_ur.spines['left'].set_visible(False)
    ax_ur.spines['bottom'].set_visible(False)
    ax_ur.tick_params('both', right=True, left=False,
                      labelleft=False, top=True, bottom=False,
                      labelbottom=False, which='both')

    # Set tickmarks for positive selection
    if gammapos1 != gammapos2:
        ax_ur.set_xticks([gammapos1, gammapos2])
        ax_ur.set_yticks([gammapos1, gammapos2])
    else:
        ax_ur.set_xticks([gammapos1])
        ax_ur.set_yticks([gammapos1])

    ax_ll.set_xlabel(xlabel, fontsize='large')
    ax_ll.set_ylabel(ylabel, fontsize='large')

    if colorbar:
        ax = fig.add_subplot(gs[1,2])
        cb = fig.colorbar(mappable, cax=ax, use_gridspec=True)
        if logweight:
            cb.set_label('Probability')
    fig.subplots_adjust(top=0.99, right=0.82, bottom=0.19, left=0.18)

    return fig