Reputation: 1946
My dataset contains > 500 observations of match activities performed by individual athletes at different locations and recorded over the duration of a soccer match. An example of my dataset is below, where each symbol refers to a match activity. For example, KE
is Kick Effective, recorded at 1 minute in the Defense
.
# Example data
df <- data.frame(Symbol = c('KE', 'TE', 'TE', 'TI',
'KE', 'KE', 'H', 'H',
'GS', 'KE', 'TE', 'H',
'KE', 'H', 'H', 'GS'),
Location = c('Defense', 'Defense', 'Midfield', 'Forward',
'Forward', 'Midfield', 'Midfield', 'Defense',
'Defense', 'Defense', 'Forward', 'Midfield',
'Midfield', 'Defense', 'Defense', 'Midfield'),
Time = c(1, 2, 3, 6,
15, 16, 16, 20,
22, 23, 26, 26,
27, 28, 28, 30))
I wish to visualise this data, by plotting the match activities over time at each location in ggplot2
.
# Load required package
require(ggplot2)
# Order factors for plotting
df$Location <- factor(df$Location, levels = c("Defense", "Midfield", "Forward"))
# Plot
ggplot(df, x = Time, y = Location) +
geom_text(data=df,
aes(x = Time, y = Location,
label = Symbol), size = 4) +
theme_classic()
However, some of the geom_text
labels overlap one another. I have tried jitter
but then I lose meaning of where the activity occurs on the soccer pitch. Unfortunately, check_overlap=TRUE
removes any overlapped symbols. I wish to keep the symbols in the same text direction.
Although the symbols are plotted at the time they occur, I am happy to adjust the time slightly (aware they will no longer perfectly align on the plot) to ensure the geom_text
symbols are visible. I can do this manually by shifting the Time
of each overlapped occurrence forward or back, but with such a big dataset this would take a very long time.
A suggestion was to use ggrepel
and I did this below, although it alters the geom_text
in the y-axis which is not what I am after.
library(ggrepel)
ggplot(df, x = Time, y = Location) +
geom_text_repel(aes(Time, Location, label = Symbol))
Is there a way I can check for overlap and automatically adjust the symbols, to ensure they are visible and still retain meaning on the y-axis? Perhaps one solution could be to find each Location
and if a Symbol
is within two minutes of another in the same Location
, Time
is adjusted.
Any help would be greatly appreciated.
Upvotes: 3
Views: 8807
Reputation: 56149
We could add points, then use ggrepel
with minimum line length to points from text labels.
library(ggrepel) # ggrepel_0.6.5 ggplot2_2.2.1
ggplot(df, aes(x = Time, y = Location, label = Symbol)) +
geom_point() +
geom_text_repel(size = 4, min.segment.length = unit(0.1, "lines")) +
theme_classic()
Or we could try and use development version with "direction" argument.
ggplot(df, aes(x = Time, y = Location, label = Symbol)) +
geom_text_repel(size = 4, direction = "x") +
theme_classic()
Upvotes: 5