Repository navigation
Expand file tree
/
Copy pathplotting.Rmd
More file actions
303 lines (224 loc) · 11.2 KB
/
Copy pathplotting.Rmd
File metadata and controls
303 lines (224 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
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
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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
---
title: "Example: textual data visualization"
author: Kenneth Benoit, Stefan Müller, and Adam Obeng
output:
html_document:
toc: true
---
```{r, echo=FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "##")
```
This vignette walks through various plot options available in **quanteda.textplots** through the `textplot_*` functions.
```{r, message=FALSE}
library("quanteda")
library("quanteda.textplots")
```
## Wordcloud
The frequency of features can be plotted as a wordcloud using `textplot_wordcloud()`.
```{r eval=TRUE, fig.width=8, fig.height=8}
dfmat_inaug <- corpus_subset(data_corpus_inaugural, Year <= 1826) |>
tokens(remove_punct = TRUE) |>
tokens_remove(pattern = stopwords('english')) |>
dfm() |>
dfm_trim(min_termfreq = 10, verbose = FALSE)
set.seed(100)
textplot_wordcloud(dfmat_inaug)
```
You can also plot a "comparison cloud", but this can only be done with fewer than eight documents:
```{r eval=TRUE, fig.width=10, fig.height=8}
corpus_subset(data_corpus_inaugural,
President %in% c("Washington", "Jefferson", "Madison")) |>
tokens(remove_punct = TRUE) |>
tokens_remove(stopwords("english")) |>
dfm() |>
dfm_group(groups = President) |>
dfm_trim(min_termfreq = 5, verbose = FALSE) |>
textplot_wordcloud(comparison = TRUE)
```
Plot will pass through additional arguments to the underlying call to `wordcloud`.
```{r eval=TRUE, fig.width=8, fig.height=8}
textplot_wordcloud(dfmat_inaug, min_count = 10,
color = c('red', 'pink', 'green', 'purple', 'orange', 'blue'))
```
## Lexical dispersion plot
Plotting a `kwic` object produces a lexical dispersion plot which allows us to visualize the occurrences of particular terms throughout the text. We call these "x-ray" plots due to their similarity to the data produced by [Amazon's "x-ray" feature for Kindle books](https://en.wikipedia.org/wiki/X-Ray_(Amazon_Kindle)).
```{r eval=TRUE, fig.width=8, fig.height=4}
toks_corpus_inaugural_subset <-
corpus_subset(data_corpus_inaugural, Year > 1949) |>
tokens()
kwic(toks_corpus_inaugural_subset, pattern = "american") |>
textplot_xray()
```
You can also pass multiple kwic objects to `plot` to compare the dispersion of different terms:
```{r eval=TRUE, fig.width=8, fig.height=4}
textplot_xray(
kwic(toks_corpus_inaugural_subset, pattern = "american"),
kwic(toks_corpus_inaugural_subset, pattern = "people"),
kwic(toks_corpus_inaugural_subset, pattern = "communist")
)
```
If you're only plotting a single document, but with multiple keywords, then the keywords are displayed one below the other rather than side-by-side.
```{r eval=TRUE, fig.width=8, fig.height=1.25}
require("readtext")
data_char_mobydick <- as.character(readtext("http://www.gutenberg.org/cache/epub/2701/pg2701.txt"))
names(data_char_mobydick) <- "Moby Dick"
textplot_xray(
kwic(tokens(data_char_mobydick), pattern = "whale"),
kwic(tokens(data_char_mobydick), pattern = "ahab")
)
```
You might also have noticed that the x-axis scale is the absolute token index for single texts and relative token index when multiple texts are being compared. If you prefer, you can specify that you want an absolute scale:
```{r eval=TRUE, fig.width=8, fig.height=4}
textplot_xray(
kwic(toks_corpus_inaugural_subset, pattern = "american"),
kwic(toks_corpus_inaugural_subset, pattern = "people"),
kwic(toks_corpus_inaugural_subset, pattern = "communist"),
scale = "absolute"
)
```
In this case, the texts may not have the same length, so the tokens that don't exist in a particular text are shaded in grey.
## Modifying lexical dispersion plots
The object returned is a ggplot object, which can be modified using ggplot:
```{r eval=TRUE, fig.width=8, fig.height=4}
library("ggplot2")
theme_set(theme_bw())
g <- textplot_xray(
kwic(toks_corpus_inaugural_subset, pattern = "american"),
kwic(toks_corpus_inaugural_subset, pattern = "people"),
kwic(toks_corpus_inaugural_subset, pattern = "communist")
)
g + aes(color = keyword) +
scale_color_manual(values = c("blue", "red", "green")) +
theme(legend.position = "none")
```
## Frequency plots
You can plot the frequency of the top features in a text using `topfeatures`.
```{r eval=TRUE, fig.width=8, fig.height=8}
library("quanteda.textstats")
tstat_freq_inaug <- textstat_frequency(dfmat_inaug, n = 100)
ggplot(tstat_freq_inaug, aes(x = frequency, y = reorder(feature, frequency))) +
geom_point() +
labs(x = "Frequency", y = "Feature")
```
If you wanted to compare the frequency of a single term across different texts, you can also use `textstat_frequency`, group the frequency by speech and extract the term.
```{r eval=TRUE, fig.width=8, fig.height=5}
# Create document-level variable with year and president
# Get frequency grouped by president
freq_grouped <- textstat_frequency(dfm(toks_corpus_inaugural_subset),
groups = President)
# Filter the term "american"
freq_american <- subset(freq_grouped, freq_grouped$feature %in% "american")
ggplot(freq_american, aes(x = frequency, y = group)) +
geom_point() +
scale_x_continuous(limits = c(0, 14), breaks = c(seq(0, 14, 2))) +
labs(x = "Frequency", y = NULL,
title = 'Frequency of "american"')
```
The above plots are raw frequency plots. For relative frequency plots, (word count divided by the length of the chapter) we need to weight the document-frequency matrix first. To obtain expected word frequency per 100 words, we multiply by 100.
```{r eval=TRUE, fig.width=8, fig.height=4}
dfm_rel_freq <- dfm_weight(dfm(toks_corpus_inaugural_subset), scheme = "prop") * 100
head(dfm_rel_freq)
rel_freq <- textstat_frequency(dfm_rel_freq, groups = dfm_rel_freq$President)
# Filter the term "american"
rel_freq_american <- subset(rel_freq, feature %in% "american")
ggplot(rel_freq_american, aes(x = group, y = frequency)) +
geom_point() +
scale_y_continuous(limits = c(0, 0.7), breaks = c(seq(0, 0.7, 0.1))) +
xlab(NULL) +
ylab("Relative frequency") +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
```
Finally, `texstat_frequency` allows to plot the most frequent words in terms of relative frequency by group.
```{r eval=TRUE, fig.width=8, fig.height=6}
dfmat_weight_pres <- data_corpus_inaugural |>
corpus_subset(Year > 2000) |>
tokens(remove_punct = TRUE) |>
tokens_remove(stopwords("english")) |>
dfm() |>
dfm_weight(scheme = "prop")
# Calculate relative frequency by president
dat_freq_weight <- textstat_frequency(dfmat_weight_pres, n = 10,
groups = President)
ggplot(data = dat_freq_weight, aes(x = nrow(dat_freq_weight):1, y = frequency)) +
geom_point() +
facet_wrap(~ group, scales = "free") +
coord_flip() +
scale_x_continuous(breaks = nrow(dat_freq_weight):1,
labels = dat_freq_weight$feature) +
labs(x = NULL, y = "Relative frequency")
```
## Plot "keyness" in a target and reference group
If you want to compare the differential associations of keywords in a target and reference group, you can calculate "keyness" which is based on `textstat_keyness`.
In this example, we compare the inaugural speech by Donald Trump with the speeches by Barack Obama.
```{r fig.width=8, fig.height=7}
# Only select speeches by Obama and Trump
corp_pres <- corpus_subset(data_corpus_inaugural,
President %in% c("Obama", "Trump"))
# Create a dfm grouped by president
dfmat_pres <- tokens(corp_pres, remove_punct = TRUE) |>
tokens_remove(stopwords("english")) |>
tokens_group(groups = President) |>
dfm()
# Calculate keyness and determine Trump as target group
tstat_keyness <- textstat_keyness(dfmat_pres, target = "Trump")
# Plot estimated word keyness
textplot_keyness(tstat_keyness)
# Plot without the reference text (in this case Obama)
textplot_keyness(tstat_keyness, show_reference = FALSE)
```
## Plot fitted scaling models
You can also plot fitted Wordscores (Laver et al., 2003) or Wordfish scaling models (Slapin and Proksch, 2008).
### Wordscores
Wordscores is a scaling procedure for estimating policy positions or scores (Laver et al., 2003). Known scores are assigned to so called reference texts in order to infer the positions of new documents ("virgin texts"). You can plot the position of words (features) against the logged term frequency, or the position of the documents.
```{r eval=TRUE, fig.width=8, fig.height=6}
library("quanteda.textmodels")
# Transform corpus to dfm
dfmat_ie <- data_corpus_irishbudget2010 |>
tokens() |>
dfm()
# Set reference scores
refscores <- c(rep(NA, 4), 1, -1, rep(NA, 8))
# Predict Wordscores model
tmod_ws <- textmodel_wordscores(dfmat_ie, y = refscores, smooth = 1)
# Plot estimated word positions (highlight words and print them in red)
textplot_scale1d(tmod_ws,
highlighted = c("minister", "have", "our", "budget"),
highlighted_color = "red")
# Get predictions
pred_ws <- predict(tmod_ws, se.fit = TRUE)
# Plot estimated document positions and group by "party" variable
textplot_scale1d(pred_ws, margin = "documents",
groups = data_corpus_irishbudget2010$party)
# Plot estimated document positions using the LBG transformation and group by "party" variable
pred_lbg <- predict(tmod_ws, se.fit = TRUE, rescaling = "lbg")
textplot_scale1d(pred_lbg, margin = "documents",
groups = data_corpus_irishbudget2010$party)
```
### Wordfish
Wordfish is a Poisson scaling model that estimates one-dimension document positions using maximum likelihood (Slapin and Proksch, 2008). Both the estimated position of words and the positions of the documents can be plotted.
```{r eval=TRUE, fig.width=8, fig.height=6}
# Estimate Wordfish model
library("quanteda.textmodels")
tmod_wf <- textmodel_wordfish(dfmat_ie, dir = c(6, 5))
# Plot estimated word positions
textplot_scale1d(tmod_wf, margin = "features",
highlighted = c("government", "global", "children",
"bank", "economy", "the", "citizenship",
"productivity", "deficit"),
highlighted_color = "red")
# Plot estimated document positions
textplot_scale1d(tmod_wf, groups = data_corpus_irishbudget2010$party)
```
### Correspondence Analysis
You can also plot the estimated document positions of a correspodence analysis (Nenadic and Greenacre 2007).
```{r eval=TRUE, fig.width=8, fig.height=6}
# Run correspondence analysis on dfm
tmod_ca <- textmodel_ca(dfmat_ie)
# Plot estimated positions and group by party
textplot_scale1d(tmod_ca, margin = "documents",
groups = data_corpus_irishbudget2010$party)
```
## References
Laver, Michael, Kenneth Benoit, and John Garry. 2003. "[Extracting Policy Positions from Political Texts Using Words as Data](http://kenbenoit.net/pdfs/WORDSCORESAPSR.pdf)." _American Political Science Review_ 97(2): 311-331.
Nenadic, Oleg and Michael Greenacre. 2007. "[Correspondence analysis in R, with two- and three-dimensional graphics: The ca package](http://www.jstatsoft.org/v20/i03/)." _Journal of Statistical Software_ 20(3): 1--13.
Slapin, Jonathan and Sven-Oliver Proksch. 2008. "[A Scaling Model for Estimating Time-Series Party Positions from Texts](https://doi.org/10.1111/j.1540-5907.2008.00338.x)." _American Journal of Political Science_ 52(3): 705--772.