R语言 使用额外的刻度和标签注解ggplot

0md85ypi  于 2023-02-01  发布在  其他
关注(0)|答案(3)|浏览(208)

你能帮我注解ggplot2散点图吗?
对于典型散点图(黑色):

df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2), decreasing = T))
ggplot(df, aes(x=x, y=y)) + geom_point()

我想以额外的刻度和自定义标签(红色)的形式添加注解:
示例图像:

q35jwt9p

q35jwt9p1#

四种解决方案。
第一个函数使用scale_x_continuous添加额外的元素,然后使用theme定制新的文本和刻度线(加上一些额外的调整)。
第二个函数使用annotate_custom创建新的grob:文本组和行组。组的位置以数据坐标表示。结果是,如果y轴的限制发生变化,组的位置也会发生变化。因此,在下面的示例中,y轴是固定的。此外,annotation_custom试图在绘图面板之外绘图。默认情况下,绘图面板的剪切是打开的。需要将其关闭。
第三种是第二种的变体(并利用here中的代码)。grob的默认坐标系是“npc”,因此在构造grob期间垂直定位grob。使用annotation_custom定位grob使用数据坐标,因此在annotation_custom中水平定位grob。因此,与第二种解决方案不同,在该解决方案中,Grob的定位与y值的范围无关。
第四种使用viewports,它为文本和刻度线的定位建立了一个更方便的单位制,在x方向上,定位使用数据坐标;在y方向上,位置使用“npc”坐标。因此,在该解决方案中,Grob的定位也与y值的范围无关。

第一个解决方案

## scale_x_continuous then adjust colour for additional element 
## in the x-axis text and ticks
library(ggplot2)
df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2), decreasing = T))

p = ggplot(df, aes(x=x, y=y)) + geom_point() + 
  scale_x_continuous(breaks = c(0,25,30,50,75,100), labels = c("0","25","xyz","50","75","100")) +
  theme(axis.text.x = element_text(color = c("black", "black", "red", "black", "black", "black")),
        axis.ticks.x = element_line(color = c("black", "black", "red", "black", "black", "black"),
                          size = c(.5,.5,1,.5,.5,.5)))

# y-axis to match x-axis
p = p + theme(axis.text.y = element_text(color = "black"),
        axis.ticks.y = element_line(color = "black"))

# Remove the extra grid line
p = p + theme(panel.grid.minor = element_blank(),
              panel.grid.major.x = element_line(color = c("white", "white", NA, "white", "white", "white")))
p

第二种解决方案

## annotation_custom then turn off clipping
library(ggplot2)
library(grid)
df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2), decreasing = T))

p = ggplot(df, aes(x=x, y=y)) + geom_point() + 
 scale_y_continuous(limits = c(0, 4)) +
 annotation_custom(textGrob("xyz", gp = gpar(col = "red")), 
        xmin=30, xmax=30,ymin=-.4, ymax=-.4) +
 annotation_custom(segmentsGrob(gp = gpar(col = "red", lwd = 2)), 
        xmin=30, xmax=30,ymin=-.25, ymax=-.15)

g = ggplotGrob(p)
g$layout$clip[g$layout$name=="panel"] <- "off"
grid.draw(g)

第三种解决方案

library(ggplot2)
library(grid)
df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2), decreasing = T))

p = ggplot(df, aes(x=x, y=y)) + geom_point() 

gtext = textGrob("xyz", y = -.05, gp = gpar(col = "red"))
gline = linesGrob(y = c(-.02, .02),  gp = gpar(col = "red", lwd = 2)) 

p = p + annotation_custom(gtext, xmin=30, xmax=30, ymin=-Inf, ymax=Inf) +
        annotation_custom(gline, xmin=30, xmax=30, ymin=-Inf, ymax=Inf)

g = ggplotGrob(p)
g$layout$clip[g$layout$name=="panel"] <- "off"
grid.draw(g)

第四种解决方案
更新至ggplot 2版本3.0.0

## Viewports
library(ggplot2)
library(grid)
df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2), decreasing = T))

(p = ggplot(df, aes(x=x, y=y)) + geom_point())

# Search for the plot panel using regular expressions
Tree = as.character(current.vpTree())
pos = gregexpr("\\[panel.*?\\]", Tree)
match = unlist(regmatches(Tree, pos))
match = gsub("^\\[(panel.*?)\\]$", "\\1", match) # remove square brackets
downViewport(match)

#######
# Or find the plot panel yourself
#  current.vpTree() # Find the plot panel
#  downViewport("panel.6-4-6-4")
#####

# Get the limits of the ggplot's x-scale, including the expansion.
x.axis.limits = ggplot_build(p)$layout$panel_params[[1]][["x.range"]]

# Set up units in the plot panel so that the x-axis units are, in effect, "native",
# but y-axis units are, in effect, "npc".
pushViewport(dataViewport(yscale = c(0, 1), xscale = x.axis.limits, clip = "off"))
grid.text("xyz", x = 30, y = -.05, just = "center", gp = gpar(col = "red"), default.units = "native")
grid.lines(x = 30, y = c(.02, -.02), gp = gpar(col = "red", lwd = 2), default.units = "native") 

upViewport(0)

fafcakar

fafcakar2#

下面的代码将得到xyz标签和它上面的一条线,你可能需要调整x和y的位置才能得到你想要的位置。

ggplot(df, aes(x=x, y=y)) + geom_point() + annotate(x=27, y=0, label="xyz", color="red") +annotate(x=27, ymin=-1, ymax=1, color="red")

如需要,请提供更多here信息。

8ehkhllq

8ehkhllq3#

**第五个解决方案:**简单地用文本层进行注解。|“或大写“i”(I)(仅适用于无衬线字体)

library(ggplot2)
df <- data.frame(x = seq(1:100), y = sort(rexp(100, 2), decreasing = T))

ggplot(df, aes(x = x, y = y)) +
  geom_point() +
  annotate(
    x = 30, y = -Inf, label = "I\nxyz", geom = "text",
    color = "red",
    lineheight = .6,
    vjust = .8
  ) +
  coord_cartesian(clip = "off")

创建于2023年1月30日,使用reprex v2.0.2

相关问题