我一直在尝试在R中绘制表格(参见:Plot a table where specific rows can be highlighted (gridExtra alternative)),而ggplot2
非常接近能够以合理的方式进行。阻止它变得容易的主要特征是你不能移动x轴,因此你不能将它用作标题。
相反,我管理了以下黑客攻击:
library(ggplot2)
library(data.table)
DT <- data.table(Meal = c("Spam", "Eggs", "Spam\nand Eggs"), Price = c(5.00,4.50, 7.00), Calories = c(200,250,400))
DT <- melt(DT, id = "Meal")
DT <- DT[, highlightCell := (value == min(value)), by = variable]
DT
Meal value variable highlightCell
1: Spam 5.0 Price FALSE
2: Eggs 4.5 Price TRUE
3: Spam\nand Eggs 7.0 Price FALSE
4: Spam 200.0 Calories TRUE
5: Eggs 250.0 Calories FALSE
6: Spam\nand Eggs 400.0 Calories FALSE
table_theme <- theme(axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
panel.background=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
plot.background=element_blank())
cellfontsize <- 12
headerfontsize <- 7
headerColour <- "grey"
ggplot(DT, aes(x = variable, y=Meal, label = value, fill = highlightCell, xmin = as.numeric(factor(variable)) - 0.5, xmax = as.numeric(factor(variable)) + 0.5, ymin = as.numeric(factor(Meal)) - 0.5, ymax = as.numeric(factor(Meal)) + 0.5)) +
# This does the cells
geom_rect() + geom_text(size = cellfontsize) +
# Next four lines do the headers (ugly)
geom_rect(aes(ymin = length(levels(factor(Meal))) + 0.5, ymax = length(levels(factor(Meal))) + 1.5), fill = headerColour) +
geom_rect(aes(xmin = -0.5, xmax=0.5), fill = headerColour) +
geom_text(aes(y = length(levels(factor(Meal))) + 1, label = variable), size = headerfontsize) +
geom_text(aes(x = 0, label = Meal), size = headerfontsize) +
table_theme + coord_cartesian(xlim=c(-1,3), ylim=c(-1,5))
理想情况下,为了让它看起来像ggplot,我想把上面的行包起来,这样他们就可以了解ggplot命令中的美学,但我不知道如何“访问”这些信息来创建一个新的geom_
类型函数。
例如,理想的语法可能类似于:
ggplot(DT, aes(x=variable, y=Meal, label=value, fill=highlightCell)) +
geom_tablecells() +
geom_tablerowheader() + geom_tablecolheader() + theme_table()
任何人都可以指出如何将上述内容包装到新的geom函数中吗?
我试过了,但这不起作用:
geom_tablecells <- function(...) {
return(geom_test(...) + geom_rect(..., size = cellfontsize))
}