error adding grid.text to ggplot

2020-03-26 03:39发布

I am trying to use grid.text in ggplot2 to add a textbox to my plot. The plot works fine by itself, but when I add the grid.text command, I get the error "Don't know how to add o to a plot". If Is use last_plot(), I still get the error, but the letter shows up on the graph - BUT will not save with the rest of the plot. data set and commands below:

foldchange  order
1.583591249 1c
1.973012368 1c
1.339505031 1c
0.776845711 2c
1.004515622 2c
1.225864907 2c
13.27371225 3c
7.599476289 3c
10.74132453 3c
3.347536996 4c
4.286202467 4c
3.612756449 4c
17.40825874 5c
20.61039144 5c

ggplot(test, aes(order, foldchange))  + geom_point()  #this part works fine
+ grid.text(label="a", x=.18, y=.9) +  #this part gives me the error

Thanks in advance!

标签: r ggplot2
1条回答
【Aperson】
2楼-- · 2020-03-26 04:11

That's because grid.text is part of grid, not ggplot. Furthermore, grid.text only plots something it doesn't add it to the underlying structure of the ggplot object. You are looking for annotate.

ggplot(test, aes(order, foldchange))  + geom_point() +
annotate(geom = "text", label="a", x=.18, y=.9)

enter image description here

This plot was produced with:

ggplot(test, aes(order, foldchange))  + geom_point() +
annotate(geom = "text", label="a", x=5, y=.9)

because x = 0.18 wouldn't show.

查看更多
登录 后发表回答