library(dplyr)
library(tibble)
mtcars %>%
group_by(cyl) %>%
summarize(wt = mean(wt), mpg = mean(mpg)) %>%
ungroup() %>%
mutate(wt = sprintf("%.2f", wt),
mpg = sprintf("%.1f", mpg)) -> tb
df <- tibble(x = 5.45, y = 34, tb = list(tb))
# using defaults
ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
geom_point() +
geom_table(data = df,
aes(x = x, y = y, label = tb))
ggplot(mtcars,
aes(wt, mpg, colour = factor(cyl))) +
geom_point() +
geom_table(data = df,
aes(x = x, y = y, label = tb),
table.rownames = TRUE,
table.theme = ttheme_gtstripes)
# settings aesthetics to constants
ggplot(mtcars,
aes(wt, mpg, colour = factor(cyl))) +
geom_point() +
geom_table(data = df,
aes(x = x, y = y, label = tb),
color = "red", fill = "#FFCCCC",
family = "serif", size = 5,
angle = 90, vjust = 0)
# passing a theme constructor as argument
ggplot(mtcars,
aes(wt, mpg, colour = factor(cyl))) +
geom_point() +
geom_table(data = df,
aes(x = x, y = y, label = tb),
table.theme = ttheme_gtminimal) +
theme_classic()
df2 <- tibble(x = 5.45,
y = c(34, 29, 24),
x1 = c(2.29, 3.12, 4.00),
y1 = c(26.6, 19.7, 15.1),
cyl = c(4, 6, 8),
tb = list(tb[1, 1:3], tb[2, 1:3], tb[3, 1:3]))
# mapped aesthetics
ggplot(mtcars,
aes(wt, mpg, color = factor(cyl))) +
geom_point() +
geom_table(data = df2,
inherit.aes = TRUE,
mapping = aes(x = x, y = y, label = tb))
# nudging and segments
ggplot(mtcars,
aes(wt, mpg, color = factor(cyl))) +
geom_point(show.legend = FALSE) +
geom_table(data = df2,
inherit.aes = TRUE,
mapping = aes(x = x1, y = y1, label = tb),
nudge_x = 0.7, nudge_y = 3,
vjust = 0.5, hjust = 0.5,
arrow = arrow(length = unit(0.5, "lines"))) +
theme_classic()
# Using native plot coordinates instead of data coordinates
dfnpc <- tibble(x = 0.95, y = 0.95, tb = list(tb))
ggplot(mtcars,
aes(wt, mpg, colour = factor(cyl))) +
geom_point() +
geom_table_npc(data = dfnpc,
aes(npcx = x, npcy = y, label = tb))
Run the code above in your browser using DataLab