Skip to content

Lexical dispersion

Examples: Lexical dispersion

dispersion

dispersion(
    corpus: T_Frame,
    expr: IntoExpr,
    method: str | list[str],
    min_freq: int = 0,
    file_id_column: str = "file_id",
) -> T_Frame

Measure how evenly each word is spread across the files of a corpus.

Parameters:

  • corpus (DataFrame | LazyFrame) –

    Corpus to measure dispersion in.

  • expr (IntoExpr) –

    Column name or expression identifying the word/type to measure (e.g. token or lemma).

  • method (str | list of str) –

    Dispersion measure to compute, or a list of them to compute together:

    • 'range' : number of files the word occurs in
    • 'range%' : the range as a percentage of the files in the corpus
    • 'sd' : standard deviation of the per-file frequencies
    • 'cv' : coefficient of variation, sd over the mean
    • 'cv%' : the coefficient of variation as a percentage
    • 'd' : Julliand's \(D\), 1 - cv / sqrt(N - 1) for N files
    • 'da' : Burch's \(D_A\), from the average difference between pairs of files
    • 'dp' : Gries's \(D_P\), how far the word's spread over the files falls from the corpus's own
  • min_freq (int, default: 0 ) –

    Minimum corpus frequency a word needs to be reported.

  • file_id_column (str, default: "file_id" ) –

    Column holding file ids.

Returns:

  • DataFrame or LazyFrame –

    One row per word, with its corpus frequency in freq and one column per measure asked for, in the order asked for: 'range', 'range%', 'sd', 'cv', 'cv%', 'D', 'DA' or 'DP'.

Raises:

  • ValueError –

    If corpus is not a Polars DataFrame or LazyFrame, is empty, or is missing a column dispersion needs; if expr is not a column name or expression; or if method is not one of the measures listed above, or a list of them.

Notes

Rows holding a null in either expr and file_id_column are dropped.

References
  • Juilland, A., & Chang-Rodriguez, E. 1964. Frequency dictionary of Spanish words. The Hague: Mouton.
  • Gries, S. Th. 2008. Dispersions and adjusted frequencies in corpora. International Journal of Corpus Linguistics 13(4):403-437.
  • Burch, B., Egbert, J., & Biber, D. 2017. Measuring and interpreting lexical dispersion in corpus linguistics. Journal of Research Design and Statistics in Linguistics and Communication Science 3(2):189-216.

Examples:

>>> import polars_corpus as plc
>>> plc.dispersion(corpus, "lemma", "d")
>>> # Rank the reasonably frequent words from least to most evenly spread:
>>> plc.dispersion(corpus, "lemma", "d", min_freq=50).sort("D")
>>> # Several measures side by side, to see where they disagree:
>>> plc.dispersion(corpus, "lemma", ["range", "d", "da", "dp"], min_freq=50)
Source code in python/polars_corpus/dispersion.py
 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
 86
 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
def dispersion(
    corpus: T_Frame,
    expr: IntoExpr,
    method: str | list[str],
    min_freq: int = 0,
    file_id_column: str = "file_id",
) -> T_Frame:
    """
    Measure how evenly each word is spread across the files of a corpus.

    Parameters
    ----------
    corpus : DataFrame | LazyFrame
        Corpus to measure dispersion in.
    expr : IntoExpr
        Column name or expression identifying the word/type to measure
        (e.g. token or lemma).
    method : str | list of str
        Dispersion measure to compute, or a list of them to compute together:

        - 'range' : number of files the word occurs in
        - 'range%' : the range as a percentage of the files in the corpus
        - 'sd' : standard deviation of the per-file frequencies
        - 'cv' : coefficient of variation, `sd` over the mean
        - 'cv%' : the coefficient of variation as a percentage
        - 'd' : Julliand's $D$, `1 - cv / sqrt(N - 1)` for `N` files
        - 'da' : Burch's $D_A$, from the average difference between pairs of files
        - 'dp' : Gries's $D_P$, how far the word's spread over the files falls
          from the corpus's own
    min_freq : int, default 0
        Minimum corpus frequency a word needs to be reported.
    file_id_column : str, default "file_id"
        Column holding file ids.

    Returns
    -------
    DataFrame or LazyFrame
        One row per word, with its corpus frequency in `freq` and one column
        per measure asked for, in the order asked for: 'range', 'range%',
        'sd', 'cv', 'cv%', 'D', 'DA' or 'DP'.

    Raises
    ------
    ValueError
        If `corpus` is not a Polars DataFrame or LazyFrame, is empty, or is
        missing a column `dispersion` needs; if `expr` is not a column name or
        expression; or if `method` is not one of the measures listed above, or
        a list of them.

    Notes
    -----
    Rows holding a null in either `expr` and `file_id_column` are dropped.

    References
    ----------
    - Juilland, A., & Chang-Rodriguez, E. 1964. *Frequency dictionary of Spanish words.*
      The Hague: Mouton.
    - Gries, S. Th. 2008. Dispersions and adjusted frequencies in corpora. *International
      Journal of Corpus Linguistics* 13(4):403-437.
    - Burch, B., Egbert, J., & Biber, D. 2017. Measuring and interpreting lexical dispersion
      in corpus linguistics. *Journal of Research Design and Statistics in Linguistics and
      Communication Science* 3(2):189-216.

    Examples
    --------
    >>> import polars_corpus as plc
    >>> plc.dispersion(corpus, "lemma", "d")
    >>> # Rank the reasonably frequent words from least to most evenly spread:
    >>> plc.dispersion(corpus, "lemma", "d", min_freq=50).sort("D")
    >>> # Several measures side by side, to see where they disagree:
    >>> plc.dispersion(corpus, "lemma", ["range", "d", "da", "dp"], min_freq=50)
    """
    methods = check_choices(method, METHODS)
    term = as_expr(expr)
    lf = as_corpus(corpus)

    check_columns(lf, [file_id_column], param="file_id_column")
    term_name = check_expr(lf, term)

    lf = lf.select(term, file_id_column).drop_nulls()

    range_methods = [m for m in methods if m in RANGE_METHODS]
    sd_methods = [m for m in methods if m in SD_METHODS]
    frames = []

    if range_methods:
        frames.append(_dispersion_range(lf, term_name, file_id_column, range_methods))

    if sd_methods or "da" in methods:
        per_file = (
            lf.group_by(term_name, file_id_column)
            .agg(pl.len().alias("_n"))
            .with_columns(pl.col(file_id_column).n_unique().alias("_N"))
        )
        sizes = lf.group_by(file_id_column).agg(pl.len().alias("_size"))
        per_file = per_file.join(sizes, on=file_id_column).select(
            term_name,
            "_N",
            pl.col("_n").alias("_f"),
            (pl.col("_n") / pl.col("_size")).alias("_n"),
        )
        if sd_methods:
            frames.append(_dispersion_sd(per_file, term_name, sd_methods))
        if "da" in methods:
            frames.append(_dispersion_da(per_file, term_name))

    if "dp" in methods:
        frames.append(_dispersion_dp(lf, term_name, file_id_column))

    result = frames[0]
    for frame in frames[1:]:
        result = result.join(frame.drop("freq"), on=term_name)

    if min_freq:
        result = result.filter(pl.col("freq") >= min_freq)

    result = result.select(term_name, "freq", *(COLUMNS[m] for m in methods))

    return collect_like(result, corpus)

barcode_plot

barcode_plot(
    corpus: T_Frame,
    expr: IntoExpr,
    targets: str | list[str],
    ax: Axes | None = None,
    linewidth: float = 0.75,
    size: float = 200,
    margin: float | None = None,
    **kwargs,
) -> Axes

Plot the position of one or more words across a corpus as a barcode.

Each occurrence of a target word is drawn as a short vertical tick at its position in the corpus, one row per word, giving a quick visual read of how evenly a word is spread out.

Parameters:

  • corpus (DataFrame | LazyFrame) –

    Corpus to plot.

  • expr (IntoExpr) –

    Column name or expression identifying the word/type to match against targets (e.g. token or lemma).

  • targets (str | list[str]) –

    Word or words to plot, one row per word.

  • ax (Axes, default: None ) –

    Axes to draw on. A new figure and axes are created if not given.

  • linewidth (float, default: 0.75 ) –

    Width of each tick mark.

  • size (float, default: 200 ) –

    Size of each tick mark, in points squared.

  • margin (float, default: None ) –

    Extra vertical padding above the first row and below the last, in row heights. Rows are half a row apart from the edges without it.

  • **kwargs –

    Passed through to Axes.scatter.

Returns:

  • Axes –

    The matplotlib axes the plot was drawn on, one row per word in targets, in the order given.

Raises:

  • ValueError –

    If corpus is not a Polars DataFrame or LazyFrame, is empty, or cannot evaluate expr; or if expr is not a column name or expression.

Warns:

  • UserWarning –

    If a word in targets does not occur in the corpus. It still gets a row, drawn empty.

Examples:

>>> import polars_corpus as plc
>>> plc.barcode_plot(corpus, "lemma", ["cat", "dog"])
Source code in python/polars_corpus/visualizations.py
 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
 86
 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
def barcode_plot(
    corpus: T_Frame,
    expr: IntoExpr,
    targets: str | list[str],
    ax: Axes | None = None,
    linewidth: float = 0.75,
    size: float = 200,
    margin: float | None = None,
    **kwargs,
) -> Axes:
    """
    Plot the position of one or more words across a corpus as a barcode.

    Each occurrence of a target word is drawn as a short vertical tick at its
    position in the corpus, one row per word, giving a quick visual read of
    how evenly a word is spread out.

    Parameters
    ----------
    corpus : DataFrame | LazyFrame
        Corpus to plot.
    expr : IntoExpr
        Column name or expression identifying the word/type to match
        against `targets` (e.g. token or lemma).
    targets : str | list[str]
        Word or words to plot, one row per word.
    ax : Axes, optional
        Axes to draw on. A new figure and axes are created if not given.
    linewidth : float, default 0.75
        Width of each tick mark.
    size : float, default 200
        Size of each tick mark, in points squared.
    margin : float, optional
        Extra vertical padding above the first row and below the last, in
        row heights. Rows are half a row apart from the edges without it.
    **kwargs
        Passed through to `Axes.scatter`.

    Returns
    -------
    Axes
        The matplotlib axes the plot was drawn on, one row per word in
        `targets`, in the order given.

    Raises
    ------
    ValueError
        If `corpus` is not a Polars DataFrame or LazyFrame, is empty, or cannot
        evaluate `expr`; or if `expr` is not a column name or expression.

    Warns
    -----
    UserWarning
        If a word in `targets` does not occur in the corpus. It still gets a
        row, drawn empty.

    Examples
    --------
    >>> import polars_corpus as plc
    >>> plc.barcode_plot(corpus, "lemma", ["cat", "dog"])
    """
    term = as_expr(expr)
    lf = as_corpus(corpus)
    term_name = check_expr(lf, term)

    if isinstance(targets, str):
        targets = [targets]

    # Filter on the term's own column rather than on `expr`: a computed term is
    # gone from the frame by the time the select is through with it.
    data = (
        lf.with_row_index()
        .select("index", term)
        .filter(pl.col(term_name).is_in(targets))
        .with_columns(
            pl.col(term_name).replace_strict(
                {target: row for row, target in enumerate(targets)}
            )
        )
        .collect()
    )

    found = data[term_name].unique()
    if missing := [target for row, target in enumerate(targets) if row not in found]:
        warnings.warn(
            f"{', '.join(repr(target) for target in missing)} "
            f"{'do' if len(missing) > 1 else 'does'} not occur in the corpus's "
            f"{term_name!r} column",
            stacklevel=2,
        )

    if ax is None:
        _, ax = plt.subplots()

    ax.scatter(
        data["index"],
        data[term_name],
        marker="|",
        linewidth=linewidth,
        sizes=[size],
        **kwargs,
    )

    ax.set(xlabel="index")

    # Set the rows rather than autoscaling to them: a target that occurs nowhere
    # has no points to scale to, but still gets a row of its own.
    pad = 0.5 + (margin or 0)
    ax.set_yticks(range(len(targets)), targets)
    ax.set_ylim(len(targets) - 1 + pad, -pad)

    for spine in ax.spines.values():
        spine.set_visible(False)
    return ax

dispersion_plot

dispersion_plot(
    corpus: T_Frame,
    expr: IntoExpr,
    target: str,
    file_id_column: str = "file_id",
    relative: bool = True,
    ax: Axes | None = None,
    linewidth: float = 0.75,
    size: float = 200,
    margin: float | None = None,
    **kwargs,
) -> Axes

Plot the position of a word across the files of a corpus.

Each occurrence of target is drawn as a short vertical tick at its position within its file, one row per file, giving a quick visual read of how evenly the word is spread across the corpus.

Parameters:

  • corpus (DataFrame | LazyFrame) –

    Corpus to plot.

  • expr (IntoExpr) –

    Column name or expression identifying the word/type to match against target (e.g. token or lemma).

  • target (str) –

    Word to plot.

  • file_id_column (str, default: "file_id" ) –

    Column holding file ids, defining the rows of the plot.

  • relative (bool, default: True ) –

    Plot each occurrence's position as a fraction of its file's length rather than a raw index, so files of different lengths line up.

  • ax (Axes, default: None ) –

    Axes to draw on. A new figure and axes are created if not given.

  • linewidth (float, default: 0.75 ) –

    Width of each tick mark.

  • size (float, default: 200 ) –

    Size of each tick mark, in points squared.

  • margin (float, default: None ) –

    Extra vertical padding above the first row and below the last, in row heights. Rows are half a row apart from the edges without it.

  • **kwargs –

    Passed through to Axes.scatter.

Returns:

  • Axes –

    The matplotlib axes the plot was drawn on, one row per file target occurs in, in corpus order.

Raises:

  • ValueError –

    If corpus is not a Polars DataFrame or LazyFrame, is empty, or is missing a column dispersion_plot needs; if expr is not a column name or expression; or if target does not occur in the corpus.

Notes

Only the files target occurs in get a row, so the plot says how evenly the word is spread over those files, not over the corpus. Read it alongside dispersion(corpus, expr, "range"), which counts them.

Examples:

>>> import polars_corpus as plc
>>> plc.dispersion_plot(corpus, "lemma", "whale")
Source code in python/polars_corpus/visualizations.py
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
def dispersion_plot(
    corpus: T_Frame,
    expr: IntoExpr,
    target: str,
    file_id_column: str = "file_id",
    relative: bool = True,
    ax: Axes | None = None,
    linewidth: float = 0.75,
    size: float = 200,
    margin: float | None = None,
    **kwargs,
) -> Axes:
    """
    Plot the position of a word across the files of a corpus.

    Each occurrence of `target` is drawn as a short vertical tick at its
    position within its file, one row per file, giving a quick visual read
    of how evenly the word is spread across the corpus.

    Parameters
    ----------
    corpus : DataFrame | LazyFrame
        Corpus to plot.
    expr : IntoExpr
        Column name or expression identifying the word/type to match
        against `target` (e.g. token or lemma).
    target : str
        Word to plot.
    file_id_column : str, default "file_id"
        Column holding file ids, defining the rows of the plot.
    relative : bool, default True
        Plot each occurrence's position as a fraction of its file's length
        rather than a raw index, so files of different lengths line up.
    ax : Axes, optional
        Axes to draw on. A new figure and axes are created if not given.
    linewidth : float, default 0.75
        Width of each tick mark.
    size : float, default 200
        Size of each tick mark, in points squared.
    margin : float, optional
        Extra vertical padding above the first row and below the last, in
        row heights. Rows are half a row apart from the edges without it.
    **kwargs
        Passed through to `Axes.scatter`.

    Returns
    -------
    Axes
        The matplotlib axes the plot was drawn on, one row per file `target`
        occurs in, in corpus order.

    Raises
    ------
    ValueError
        If `corpus` is not a Polars DataFrame or LazyFrame, is empty, or is
        missing a column `dispersion_plot` needs; if `expr` is not a column name
        or expression; or if `target` does not occur in the corpus.

    Notes
    -----
    Only the files `target` occurs in get a row, so the plot says how evenly the
    word is spread over those files, not over the corpus. Read it alongside
    `dispersion(corpus, expr, "range")`, which counts them.

    Examples
    --------
    >>> import polars_corpus as plc
    >>> plc.dispersion_plot(corpus, "lemma", "whale")
    """
    term = as_expr(expr)
    lf = as_corpus(corpus)

    check_columns(lf, [file_id_column], param="file_id_column")
    term_name = check_expr(lf, term)

    position = pl.int_range(1, pl.len() + 1)
    if relative:
        position = position / pl.len()
    # Filter on the term's own column rather than on `expr`: a computed term is
    # gone from the frame by the time the select is through with it.
    data = (
        lf.select(position.over(file_id_column).alias("index"), file_id_column, term)
        .filter(pl.col(term_name) == target)
        .collect()
    )

    if data.height == 0:
        raise ValueError(
            f"{target!r} does not occur in the corpus's {term_name!r} column, "
            f"so there is nothing to plot"
        )

    if ax is None:
        _, ax = plt.subplots()

    ax.scatter(
        data["index"],
        data[file_id_column],
        marker="|",
        linewidth=linewidth,
        sizes=[size],
        **kwargs,
    )

    ax.set(xlabel="relative index" if relative else "index")

    # Rows read top to bottom, in corpus order, as in `barcode_plot`.
    pad = 0.5 + (margin or 0)
    ax.set_ylim(data[file_id_column].n_unique() - 1 + pad, -pad)

    for spine in ax.spines.values():
        spine.set_visible(False)
    return ax