问题
Trying to improve this code. What I have worked up works but looks ugly and is VERY clumsy.
Looking for a ggplot method or something that is more user friendly. Would appreciate the tips and advice.
library("dplyr")
thi <- data.frame(RH = c(1,1,1,2,2,2,3,3,3), T = c(1,2,3,1,2,3,1,2,3), THI = c(8,8,5,7,5,10,5,8,7))
table_thi <- tapply(thi$THI, list(thi$RH, thi$T), mean) %>% as.table()
x = 1:ncol(table_thi)
y = 1:nrow(table_thi)
centers <- expand.grid(y,x)
image(x, y, t(table_thi),
col = c("lightgoldenrod", "darkgoldenrod", "darkorange"),
breaks = c(5,7,8,9),
xaxt = 'n',
yaxt = 'n',
xlab = '',
ylab = '',
ylim = c(max(y) + 0.5, min(y) - 0.5))
text(round(centers[,2],0), round(centers[,1],0), c(table_thi), col= "black")
mtext(paste(attributes(table_thi)$dimnames[[2]]), at=1:ncol(table_thi), padj = -1)
mtext(attributes(table_thi)$dimnames[[1]], at=1:nrow(table_thi), side = 2, las = 1, adj = 1.2)
abline(h=y + 0.5)
abline(v=x + 0.5)
回答1:
How about this:
library(dplyr)
library(ggplot2)
thi <- data.frame(
RH = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
T = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
THI = c(8, 8, 5, 7, 5, 10, 5, 8, 7)
)
names(thi) = c('col1', 'col2', 'thi')
ggplot(thi, aes(x = col1, y = col2, fill = factor(thi), label = thi)) +
geom_tile() +
geom_text()
Or depending on whether thi
is really factor
(discrete) or continuous variable, you may want something like this:
ggplot(thi, aes(x = col1, y = col2, fill = thi, label = thi)) +
geom_tile() +
geom_text(color = 'white')
Note: You probably want to avoid using column or variable names that are reserved words or abbreviations (e.g. avoid calling something T
because that's an abbreviation for the keyword TRUE
). In the code above, I renamed the columns of your data.frame.
Since the question says conditional formatting of a table, however, you may want to consider the gt package:
library(gt)
thi %>% gt()
Or this:
thi %>% gt() %>%
data_color(
columns = vars(thi),
colors = scales::col_factor(
palette = "Set1",
domain = NULL
))
Or maybe this:
thi %>% gt() %>%
tab_style(
style = cells_styles(
bkgd_color = "#F9E3D6",
text_style = "italic"),
locations = cells_data(
columns = vars(thi),
rows = thi <= 7
)
)
来源:https://stackoverflow.com/questions/55066716/conditional-formatting-of-table-in-r-a-better-way