【发布时间】:2021-01-25 14:57:41
【问题描述】:
我有一个类似于以下示例的数据集
df <- structure(list(Species = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L,3L,
1L, 2L, 3L), .Label = c("setosa", "versicolor", "virginica"), class =
"factor"), flower_att = c("Sepal.Length", "Sepal.Length", "Sepal.Length",
"Sepal.Width", "Sepal.Width", "Sepal.Width", "Petal.Length", "Petal.Length",
"Petal.Length", "Petal.Width", "Petal.Width", "Petal.Width"), measurement =
c(5.1, 7, 6.3, 3.5, 3.2, 3.3, 1.4, 4.7, 6, 0.2, 1.4, 2.5), month =
c("January", "February", "January", "February", "January", "February",
"January", "February", "January", "February", "January", "February")),
row.names = c(NA,-12L), class = "data.frame")
我想并排显示每个物种和月份的萼片长度和宽度。我希望使用热图中的对角分割单元来执行此操作,该单元具有 2 个不同的颜色图例,即长度为红色,宽度为蓝色。如果可能的话,我希望将值显示在单元格段中。 到目前为止,我的搜索找到了最接近的 example,但我正在寻找一个可行的 ggplot 版本。
我自己的尝试目前如下所示。我不知道如何分解细胞。
ggplot(df, aes(x=month, y=Species)) + geom_tile(aes(fill=measurement),
color="black") + theme(axis.text.x = element_text(angle=45, hjust = .5)) +
geom_text(aes(label = round(measurement, .1))) + scale_fill_gradient(low =
"white", high = "red")
更新
在互联网上进行了一些认真的挖掘之后,我发现了一个使用 geom_segment 和 geom_text_repel 的潜在选项,见下文。谁能告诉我这是否是一个可行的选择?如果是这样,我怎样才能使其满足上述要求?
我愿意将scale_fill_gradient 切换到scale_fill_manual 或其他替代方案,我的主要目标是让所有数据并排显示
ggplot(df, aes(x=month, y=Species)) +
geom_tile(aes(fill=measurement), color="black") +
theme(axis.text.x = element_text(angle=45, hjust = .5)) +
geom_text_repel(aes(label = round(measurement, .1))) +
scale_fill_gradient(low = "white", high = "red")
gb <- ggplot_build(p)
p + geom_segment(data=gb$data[[1]],
aes(x=xmin, xend=xmax, y=ymin, yend=ymax), color="black")
【问题讨论】:
-
到目前为止你尝试了什么?
-
嗨,迈克,到目前为止,我使用了以下内容,但我无法锻炼如何执行拆分
ggplot(df, aes(x=month, y=Species)) + geom_tile(aes(fill=measurement), color="black") + theme(axis.text.x = element_text(angle=45, hjust = .5)) + geom_text(aes(label = round(measurement, .1))) + scale_fill_gradient(low = "white", high = "red") -
好问题!我不知道该怎么做,我还会编辑您的问题以将 ggplot 代码放在那里,以便其他人可以帮助解决问题。
-
在这方面似乎还有其他努力,例如this post。
-
感谢@Ben 的链接我尝试了提问者的示例,但结果与他们得到的不同。但我会看看我是否可以解决它:)