我碰到了一个博客帖子Favillae: Thermometer Plots in R,其中显示了下面的图,但没有提供所使用的R代码。
鉴于这些数据,我如何生成下面的图?
roper_data <- structure(list(govt = c(74L, 66L, 64L, 53L, 43L, 39L, 31L), priv.co = c(64L,
38L, 50L, 20L, 19L, 13L, 12L), police = c(27L, 34L, 25L, 22L,
50L, 15L, 20L), ccc = c(44L, 10L, 13L, 7L, 8L, 10L, 5L)), class = "data.frame", row.names = c("Employment records",
"Psychiatric history", "Health records", "Memberships, Associations",
"Traffic violations", "Tax returns", "Sexual history"))
答案 0 :(得分:3)
首先,您需要将数据从宽格式转换为长格式:
df$Var <- rownames(df)
df2 <- reshape2::melt(df, "Var")
接下来,我们绘制两组Barplots。第一层获取轮廓(最大为100),第二层为实际数据。我们使用facet_grid()
对齐它们。
ggplot(df2, aes(1, value)) +
# put 100 on as y to get the outline
geom_bar(aes(y = 100), stat = "identity",
color = "black", fill = "white") +
geom_bar(stat = "identity") +
facet_grid(variable ~ Var) +
labs(y = NULL,
x = NULL) +
theme_classic() +
theme(axis.ticks.x = element_blank(),
axis.text.x = element_blank())
您甚至可以使用以下代码(在50%处添加行并删除所有轴)添加更多视觉调整:
ggplot(df2, aes(1, value)) +
# put line at 50%
geom_segment(aes(x = 0.2, xend = 1.8, y = 50, yend = 50), data.frame(1)) +
# put 100 on as y to get the outline
geom_bar(aes(y = 100), stat = "identity",
color = "black", fill = "white") +
geom_bar(stat = "identity") +
facet_grid(variable ~ Var) +
labs(y = NULL,
x = NULL) +
theme_void()
答案 1 :(得分:0)
或者,使用基本R图形中的符号功能
roper <- as.matrix(roper_data)/100
z <- as.vector(roper)
x <- rep(sapply(1:4, function(x) {rep(x, 7)}),1)
y <- rep(7:1, 4)
hist_type = c("sxhist", "tax", "traffic", "assoc", "health", "psychhist", "emplhist")
par(mar=c(6, 6, 2, 2))
symbols(x, y, thermometers = cbind(0.15, 0.2, z), inches = 0.8, fg = 1, ylab='', xlab='', yaxt='n', xaxt='n')
axis(1, at = 1:4, labels = colnames(roper))
axis(2, at = 1:7, hist_type, las = 2)
mtext("Who", 1, 3, cex = 1.5)
mtext("What", 2, 4, cex = 1.5)