gpt4 book ai didi

r - 用指定颜色的绘图区域外的形状进行注释

转载 作者:行者123 更新时间:2023-12-01 10:35:08 29 4
gpt4 key购买 nike

我需要以某种方式注释我的情节。继答案here ,我可以想出这个,

df = data.frame(y= rep(c(1:20, 1:10), 5), x=c(rep("A", 20), rep("B", 10), rep("C", 20), rep("D", 10), rep("E", 20),
rep("F", 10), rep("G", 20), rep("H", 10), rep("I", 20), rep("J", 10)),
g= c(rep(sample(1:2, 1), 20), rep(sample(1:2, 1), 10),rep(sample(1:2, 1), 20), rep(sample(1:2, 1), 10),
rep(sample(1:2, 1), 20), rep(sample(1:2, 1), 10),rep(sample(1:2, 1), 20), rep(sample(1:2, 1), 10),
rep(sample(1:2, 1), 20), rep(sample(1:2, 1), 10)))

p <- ggplot(df, aes(factor(x), y)) + geom_boxplot()+ # Base plot
theme(plot.margin = unit(c(3,1,1,1), "lines"), plot.background= element_rect(color= "transparent")) # Make room for the grob
for (i in 1:length(df$g)) {
p <- p + annotation_custom(
grob = textGrob(label = df$g[i], hjust = 0, gp = gpar(cex = 1.5)),
xmin = df$x[i], # Vertical position of the textGrob
xmax = df$x[i],
ymin = 22, # Note: The grobs are positioned outside the plot area
ymax = 22)
}

gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

这会生成此图 .

我想要在注释中使用大小为 0.6 pt 而不是 2 的蓝色三角形和蓝色“+”符号而不是 1。你能帮我解决这个问题吗?

最佳答案

您必须使用 pointsGrob 而不是 textGrob 函数。接下来是您需要添加点而不是文本标签的行。

pointsGrob(pch = ifelse(df$g[i]==1,3,17), gp = gpar(cex = 0.6,col=ifelse(df$g[i]==1,"red","blue")))

这里我用 3 表示 + 点,用 17 表示 $\triangle$ 形状。整个代码如下所示

df = data.frame(y= rep(c(1:20, 1:10), 5), x=c(rep("A", 20), rep("B", 10), rep("C", 20), rep("D", 10), rep("E", 20),
rep("F", 10), rep("G", 20), rep("H", 10), rep("I", 20), rep("J", 10)),
g= c(rep(sample(1:2, 1), 20), rep(sample(1:2, 1), 10),rep(sample(1:2, 1), 20), rep(sample(1:2, 1), 10),
rep(sample(1:2, 1), 20), rep(sample(1:2, 1), 10),rep(sample(1:2, 1), 20), rep(sample(1:2, 1), 10),
rep(sample(1:2, 1), 20), rep(sample(1:2, 1), 10)))

p <- ggplot(df, aes(factor(x), y)) + geom_boxplot()+ # Base plot
theme(plot.margin = unit(c(3,1,1,1), "lines"), plot.background= element_rect(color= "transparent")) # Make room for the grob
for (i in 1:length(df$g)) {
p <- p + annotation_custom(
grob = pointsGrob(pch = ifelse(df$g[i]==1,3,17), gp = gpar(cex = 0.6,col=ifelse(df$g[i]==1,"red","blue"))),
xmin = df$x[i], # Vertical position of the textGrob
xmax = df$x[i],
ymin = 22, # Note: The grobs are positioned outside the plot area
ymax = 22)
}

gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

生成的图如下所示

enter image description here

希望对您有所帮助。

关于r - 用指定颜色的绘图区域外的形状进行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36953833/

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