我想请问是否有人能够帮我解决以下问题: 我想将ggplot2中geom_tile热力图的每个列设置为不同宽度。
library(ggplot2)
library(data.table)
ggplot(data = melt(as.matrix(mtcars))) + geom_tile(aes(x=Var2, y=Var1,fill = value))
我希望第一列(mpg)的宽度为5,第二列为2等等。
谢谢。
geom_tile()
有一个width
参数,您可以使用它来编程设置宽度。但是,如果您不明确标签放置的位置,标签将出现在奇怪的位置上。因此,我根据指定的宽度预先计算每个标签的位置。在这里,您还需要知道您希望这些列出现的顺序,以便它们正确显示。
library(tidyverse)
# set widths of each column and calculate position for lables and boxes
widths <- tibble(param = fct_inorder(names(mtcars)),
width = c(5, 2, rep(1, 9)),
x_end = cumsum(width),
x_pos = x_end - width/2
)
# plot and specify precalculated labels
mtcars %>%
rownames_to_column("car") %>%
pivot_longer(-car, "param") %>%
left_join(., widths) %>%
ggplot(aes(x_pos, car, fill = value)) +
geom_tile(aes(width = width)) +
scale_x_continuous(breaks = widths$x_pos, labels = widths$param)
#> Joining, by = "param"
此内容由reprex package (v2.0.1)于2022-02-14创建