Saving your plots!

# Ggplot2 plots
ggsave("figs/CNC_Defs_CNC_Entries.pdf", plot = CNC_Defs_CNC_Entries, width = 10,
    height = 8, units = "in")

Density Distributions

Boxplots

The box is defined by the interquartile range (Q2-Q3). The crossbar is the median (here it’s 5). The whiskers represent max and min (not outliers). The width on the box and the whispers should match.

ggplot(seq7, aes(x = "", y = shoe.size)) + stat_boxplot(geom = "errorbar", width = 0.3) +
    xlab(NULL) + scale_y_continuous(breaks = seq(0, 10, 2), limits = c(0, 10)) +
    geom_boxplot(fill = "blue", width = 0.3) + jamie.theme
print(p1)



Violin Plot

myrainpal <- c("gray", "dodgerblue4")
ggplot(OldYoungLong, aes(who_older, dim_vals, fill = who_older)) + geom_violin(trim = FALSE,
    alpha = 0.5) + scale_fill_manual(values = myrainpal) + theme_classic() + facet_wrap(~dimension,
    ncol = 3) + stat_summary(fun.y = mean, geom = "point", shape = 23, size = 2)
ggsave("Figs/Candor_WhoOlder_Violin.pdf", width = 10, height = 8, dpi = 300)



Raincloud plot 1

Here’s a lovely combination of a raincloud plot and a boxplot

ggplot(datmlm, aes(cond, arousal)) + ggdist::stat_halfeye(adjust = 0.5, width = 0.3,
    .width = c(0.5, 1)) + geom_boxplot(width = 0.2, outlier.shape = NA) + scale_fill_manual(values = newvec) +
    jamie.theme



Raincloud Plot 2

Here’s a slightly more involved raincloud plot across many observations. Not feasible to plot points here

#Raincloud plots by category
CNC_Defs_CNC_Entries <-  ggplot(wiki_freqout, aes(x = Entry_CNC_zCat, y = Definition_CNC, fill = Entry_CNC_zCat)) + 
  ggdist::stat_halfeye(
    ## custom bandwidth
    adjust = .5,  width = 1, justification = -.25, 
    ## remove slab interval
    .width = 0, point_colour = NA) + 
  geom_boxplot(width = .30, outlier.color = NA, alpha = 0.4) + scale_fill_met_d(name="Wissing") +  theme_classic() + coord_flip() + theme(legend.position = "none")
  
ggsave("figs/CNC_Defs_CNC_Entries.pdf", plot = CNC_Defs_CNC_Entries, width = 10, height = 8, units = "in")

Barplots

Make sure you are plotting means rather than “identity”. Dodge the bars unless you want a stacked bar chart. Finally, you need stat_summary if you want to calculate and add error bars on the fly. I like the little slashes on the legend. You get those by passing “show_guide=T” to the geom_bar code.

Barplot1: Error Bars

colvec <- c("gray", "green")
ggplot(dat2, aes(x = StimCond, y = Dilation, fill = WordCond)) + geom_bar(position = "dodge",
    stat = "summary", fun.y = "mean") + scale_fill_manual(values = colvec) + stat_summary(fun.data = mean_se,
    geom = "errorbar", width = 0.2, position = position_dodge(0.9)) + jamie.theme


Barplot2: Color Aesthetics

Plotting arousal ratings of every word in Goodfellas marking all the curse words on green.

trysmooth <- onlyvals %>%
    mutate(smootharouse = zoo::rollmean(Arousal, k = 5, fill = NA))  #smooth using rolling mean, smooth the arousal time series
colvec <- c("gray", "green")
goodplot <- ggplot(trysmooth, aes(x = Order, y = smootharouse, fill = Condition)) +
    geom_col(position = "dodge") + scale_fill_manual(values = colvec) + jamie.theme
# ggsave('luciagoodfellasplot.pdf')


Barplot3: Scaling Axes and Breaks

Scale both axes, specify custom fill and color (outlines)

ggplot(diff_plot, aes(ExchangeCount, val_diff)) + jamie.theme + geom_bar(stat = "identity",
    fill = "#5B1A18", color = "gray86") + scale_x_continuous(breaks = seq(0, 140,
    10), limits = c(1, 135)) + scale_y_continuous(breaks = seq(0, 6, by = 1))



Barplot4: Word frequency in a corpus

Plots the 25 most frequent words in a language sample

words <- Corpus(VectorSource(defs_concat_cleaned$word))  #Convert to a corpus object
wtm <- TermDocumentMatrix(words)  #Convert to a term document matrix
m <- as.matrix(wtm)  #Unspool to a regular matrix
v <- sort(rowSums(m), decreasing = TRUE)
d <- data.frame(word = names(v), freq = v)
barplot(d[1:25, ]$freq, las = 2, names.arg = d[1:25, ]$word, col = "#009999", main = "Most Frequent Gaslighting Keywords",
    ylab = "Word frequencies")



Barplot5 Corpus frequency

Using base R

# Top 25 most frequent words AFTER omitting by High F grammatical markers,
# Create a frequency table
corp_freq_out <- as.data.frame(table(wiki_freqout$Definition_Clean))
names(corp_freq_out) <- c("word", "frequency")
corp_freq_out <- corp_freq_out[order(-corp_freq_out$frequency), ]
top_words_frequout <- head(corp_freq_out, 25)
top25_frequout <- ggplot(data = top_words_frequout, aes(x = reorder(word, frequency),
    y = frequency)) + geom_bar(stat = "identity", fill = "red4") + labs(title = "Top Frequency",
    x = "Word", y = "Frequency") + theme_classic() + coord_flip() + theme(legend.position = "none")

print(top25_frequout)

ggsave("figs/Top25_Freq.pdf", plot = top25_frequout, width = 10, height = 8, units = "in")



Correlation Plots

Corrplot (bells and whistles)

specify a continuous color index (custom polette). Coerce the first column to rownames or else you will get a big fat error when R tries to correlate a string with an integer.

personvars_corrplot <- Convos_Agg2Rows %>%
    select(3, 4, 6:11, 24, 31, 32, 33, 24)
people_corrs <- personvars_corrplot %>%
    dplyr::rename(c(edu = "edu_yrs", trust = "aff_trust", valence = "aff_valence",
        `n-lett` = "lex_letter_count_raw", freq = "lex_wordfreqlg10_raw", arousal = "sem_arousal",
        concrete = "sem_concreteness", WC_Raw = "TotalWC_ByConvoRaw", WC_Clean = "TotalWC_ByConvoCleanAligned",
        ContentRatio = "ContentWordRatio"))

# build correlation matrix
people_corrmat <- cor(people_corrs, method = "spearman")

# store p-values in new matrix to pass to p.mat
corr_p <- psych::corr.test(people_corrs)$p

# color palette from blue to red in increments of 20
colpal <- colorRampPalette(c("blue", "lightblue", "white", "yellow", "red"))(20)

# set sig threshold at .005 for 11 contrasts
langplot <- corrplot(people_corrmat, method = "color", type = "upper", tl.srt = 45,
    tl.cex = 1, col = colpal, tl.col = "black", diag = F, digits = 2, order = "hclust",
    p.mat = corr_p, sig.level = 0.005, insig = "blank", addgrid = T, addgrid.col = "gray",
    addCoef.col = "black", number.cex = 8/ncol(people_corrmat))
print(langplot)

# creating and saving corrplot
pdf(file = "Figs/LangPlot.pdf")
corrplot(people_corrmat, method = "color", type = "upper", tl.srt = 45, tl.cex = 1,
    col = colpal, tl.col = "black", diag = F, digits = 2, order = "hclust", p.mat = corr_p,
    sig.level = 0.005, insig = "blank", addgrid = T, addgrid.col = "gray", addCoef.col = "black",
    number.cex = 8/ncol(people_corrmat))
dev.off()



Corrplot (viridis)

Color palette- viridis

corrplot(joshcor, method = "shade", col = viridis(12), shade.col = NA, tl.col = "black",
    tl.srt = 45)



Corrplot (some bells)

Circles are scaled to indicate the strength of the correlation. Colors indicate the direction of the correlation (blue is negative, red is positive). Since this is a symmetrical matrix, I only included the upper diagonal.

corrmat <- cor(josh, use = "complete.obs")  #create a correlation matrix
corrplot(corrmat, method = "circle", type = "upper", tl.srt = 45, tl.cex = 1, col = viridis(12),
    tl.col = "black", diag = F, order = "hclust")




Dendrograms

Triangle dendrogram

Same dendrogram plotted as a triangle. There’s lots of extra ‘junk’ space at the top. If we focus on the lower leaves, we might be able to discern a bit more structure.

plt.tri <- sp.dend %>%
    set("labels_cex", 0.8) %>%
    set("branches_lwd", 1.5) %>%
    set("leaves_cex", 1.5) %>%
    set("labels_col", "blue") %>%
    raise.dendrogram(2)
plot(plt.tri, horiz = F, type = "triangle")



Heatmaps

Basic

Oh the beauty of a nice heatmap. Here’s one using our semantic data. These data represent average Likert-scale ratings on multiple semantic dimensions (color, sound, etc.) for three English words (kite, alligator, reputation). Prep the dataframe by changing it to a matrix, coercing column one to rownames

dat.1 <- dat.d[, -1]  #create a new dataframe minus the first column (eliminate what will be rownames)
rownames(dat.1) <- dat.d[, 1]
mat.1 <- as.matrix(dat.1)
jamie.colors <- colorRampPalette(c("yellow", "red"))(n = 299)
heatmap.2(mat.1, key.title = NA, dendrogram = "none", trace = "none", col = jamie.colors,
    density.info = "none", margins = c(8, 8), cexRow = 1.5)




## Contour Sort of like an interpolated heat map

all <- read.csv(here("data", "db_glascow.csv"), row.names = 1) %>%
    clean_names()
all$gls_img <- as.integer(all$gls_img)
all$gls_arousal <- as.integer(all$gls_arousal)
all$gls_aoa <- as.integer(all$gls_aoa)
ggplot(all, aes(gls_img, gls_arousal, z = gls_aoa)) + geom_contour_filled(binwidth = 0.2) +
    xlim(2, 6) + labs(fill = "AoA") + jamie.theme



Histograms

Gaussian overlay

Here’s something you don’t see every day. This histogram reflects counts from Likert-Scale ratings of the quality of pairing common English nouns (e.g., rocket) with taboo words (e.g., shit) to form new taboo compounds (e.g., shitrocket). In this particular histogram, I changed the binwidth to .10 and the y-axis to raw counts. Histogram 2 plots an overlay of a normal curve from a set of psycholinguistic norms.

ggplot(profexp2, aes(x = Qualtrics)) + geom_histogram(colour = "black", fill = "goldenrod2",
    binwidth = 0.1) + xlab("Average Likert Scale Rating") + ylab("Word Count Per Bin") +
    jamie.theme + ggtitle("profane noun compounds")



## Histogram2 facet

ggplot(Lancaster, aes(x = Olfactory)) + geom_histogram(aes(y = ..density..), colour = "black",
    fill = "green", binwidth = 0.1) + xlab("Likert Rating") + ylab("Density") + jamie.theme +
    ggtitle("dnorm gaussian overlay") + stat_function(fun = dnorm, args = list(mean = mean(Lancaster$Olfactory),
    sd = sd(Lancaster$Olfactory)), color = "black", size = 1)



density plot 1

A density plot is like a smoothed histogram. They’re quite pretty. Let’s say you want to examine two distributions, each composed of 1000 observations. It’s Philly kids vs NYC kids on some crazy standardized test. Let’s say the Philly kids score a mean of 80 (sd=2), whereas NYC kids score a mean of 90 (sd=5). The trick was adjusting the alpha on this.

col.vec <- c("goldenrod2", "blue")
ggplot(phlnyc, aes(x = test.score, fill = city)) + geom_density(alpha = 0.5, colour = "white") +
    scale_fill_manual(values = col.vec) + xlab("Test.Score") + ylab("Count") + jamie.theme +
    ggtitle("Pretty")


density 2

Two density plots overlaid from different dataframes

mean_dictionary <- mean(wiki_freqout$Definition_CNC, na.rm = TRUE)
mean_world <- mean(cnc$sem_cnc_b24, na.rm = TRUE)

dict_dense <- ggplot() + 
  geom_density(data = wiki_freqout, aes(x = Definition_CNC, fill = "Dictionary"), alpha = 0.4, color = "goldenrod2", show.legend = TRUE) + 
  geom_density(data = cnc, aes(x = sem_cnc_b24, fill = "World"), alpha = 0.4, color = "darkblue", show.legend = TRUE) +
  geom_vline(xintercept = mean_dictionary, linetype = "dotted", color = "goldenrod2") + 
  geom_vline(xintercept = mean_world, linetype = "dotted", color = "darkblue") +
  scale_fill_manual(values = c("Dictionary" = "goldenrod2", "World" = "darkblue")) +
  scale_color_manual(values = c("Dictionary" = "white", "World" = "white")) + 
  xlab("Concreteness (low to high)") + 
  jamie_theme +
  labs(title = "Density Plot with Means Annotated", 
       subtitle = paste("Mean Dictionary:", round(mean_dictionary, 2), 
                        "; Mean World:", round(mean_world, 2))) +
  theme(legend.position = c(0.9, 0.9),  # Set legend position to upper right
        legend.justification = c("right", "top"))  # Adjust justification to match position