gpt4 book ai didi

r - 使用 facet_grid 将 "title"添加到我的因子

转载 作者:行者123 更新时间:2023-12-04 11:59:45 24 4
gpt4 key购买 nike

我想使用 ggplot2 为我的因子添加文本/标题。

例如来自 {reshape2} 库的数据:

library(reshape2)
library(ggplot2)
ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1) +
facet_grid(sex ~ .)

因子标签是:女性和男性。

如何在它们上面添加标题“性”?

enter image description here

最佳答案

适配 this answer .

稍微好一点的版本。计算出它自己的宽度。

library(reshape2)
library(ggplot2)
library(grid)
library(gtable)

p = ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1) +
facet_grid(sex ~ .)

# text, size, colour for added text
text = "SEX"
size = 30
col = "red"
face = "bold"

# Convert the plot to a grob
gt <- ggplotGrob(p)

# Get the positions of the right strips in the layout: t = top, l = left, ...
strip <-c(subset(gt$layout, grepl("strip-r", gt$layout$name), select = t:r))

# Text grob
text.grob = textGrob(text, rot = -90,
gp = gpar(fontsize = size, col = col, fontface = face))

# New column to the right of current strip
# Adjusts its width to text size
width = unit(2, "grobwidth", text.grob) + unit(1, "lines")
gt <- gtable_add_cols(gt, width, max(strip$r))

# Add text grob to new column
gt <- gtable_add_grob(gt, text.grob,
t = min(strip$t), l = max(strip$r) + 1, b = max(strip$b))

# Draw it
grid.newpage()
grid.draw(gt)

原装
library(reshape2)
library(ggplot2)
library(grid)
library(gtable)

p = ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1) +
facet_grid(sex ~ .)

# Convert the plot to a grob
gt <- ggplotGrob(p)

# Get the positions of the right strips in the layout: t = top, l = left, ...
strip <-c(subset(gt$layout, grepl("strip-r", gt$layout$name), select = t:r))

# New column to the right of current strip
# Adjust the width to suit
gt <- gtable_add_cols(gt, unit(3, "lines"), max(strip$r))

# Add text grob to new column; adjust cex (i.e., size) to suit
gt <- gtable_add_grob(gt,
textGrob("SEX", rot = -90,
gp = gpar(cex = 2, fontface = "bold", col = "RED")),
t = min(strip$t), l = max(strip$r) + 1, b = max(strip$b))

# Draw it
grid.newpage()
grid.draw(gt)

enter image description here

关于r - 使用 facet_grid 将 "title"添加到我的因子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36121301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com