我想在ggplot2中創建的圖下方顯示一些有關數據的信息。我想使用圖的X軸座標來繪製N變量,但Y座標需要距離屏幕底部10%。事實上,所需的Y座標已經在y_pos變量的數據框中。在ggplot2生成的圖下方顯示文本
1)創建的實際圖下方的空情節,使用相同的比例,然後使用geom_text在空白情節繪製數據:
我可以用GGPLOT2想到的3種方法。 This approach種類的作品,但是非常複雜。
2)使用geom_text
繪製數據,但以某種方式使用y座標作爲屏幕百分比(10%)。這將迫使數字顯示在圖下方。我無法弄清楚正確的語法。
3)使用grid.text顯示文本。我可以很容易地將它設置在屏幕底部的10%處,但我無法確定X座標是如何設置爲與劇情相匹配的。我試圖使用grconvert來捕獲最初的X位置,但無法讓它工作。
下面是基本情節與僞數據:
graphics.off() # close graphics windows
library(car)
library(ggplot2) #load ggplot
library(gridExtra) #load Grid
library(RGraphics) # support of the "R graphics" book, on CRAN
#create dummy data
test= data.frame(
Group = c("A", "B", "A","B", "A", "B"),
x = c(1 ,1,2,2,3,3),
y = c(33,25,27,36,43,25),
n=c(71,55,65,58,65,58),
y_pos=c(9,6,9,6,9,6)
)
#create ggplot
p1 <- qplot(x, y, data=test, colour=Group) +
ylab("Mean change from baseline") +
geom_line()+
scale_x_continuous("Weeks", breaks=seq(-1,3, by = 1)) +
opts(
legend.position=c(.1,0.9))
#display plot
p1
下面的受試者顯示數字的改性gplot,然而它們被顯示內的曲線圖。他們強制延長Y量表。我想在下面的圖表中顯示這些數字。
p1 <- qplot(x, y, data=test, colour=Group) +
ylab("Mean change from baseline") +
geom_line()+
scale_x_continuous("Weeks", breaks=seq(-1,3, by = 1)) +
opts(plot.margin = unit(c(0,2,2,1), "lines"),
legend.position=c(.1,0.9))+
geom_text(data = test,aes(x=x,y=y_pos,label=n))
p1
顯示數字的另一種方法涉及在實際繪圖下方創建一個虛擬繪圖。下面是代碼:
graphics.off() # close graphics windows
library(car)
library(ggplot2) #load ggplot
library(gridExtra) #load Grid
library(RGraphics) # support of the "R graphics" book, on CRAN
#create dummy data
test= data.frame(
group = c("A", "B", "A","B", "A", "B"),
x = c(1 ,1,2,2,3,3),
y = c(33,25,27,36,43,25),
n=c(71,55,65,58,65,58),
y_pos=c(15,6,15,6,15,6)
)
p1 <- qplot(x, y, data=test, colour=group) +
ylab("Mean change from baseline") +
opts(plot.margin = unit(c(1,2,-1,1), "lines")) +
geom_line()+
scale_x_continuous("Weeks", breaks=seq(-1,3, by = 1)) +
opts(legend.position="bottom",
legend.title=theme_blank(),
title.text="Line plot using GGPLOT")
p1
p2 <- qplot(x, y, data=test, geom="blank")+
ylab(" ")+
opts( plot.margin = unit(c(0,2,-2,1), "lines"),
axis.line = theme_blank(),
axis.ticks = theme_segment(colour = "white"),
axis.text.x=theme_text(angle=-90,colour="white"),
axis.text.y=theme_text(angle=-90,colour="white"),
panel.background = theme_rect(fill = "transparent",colour = NA),
panel.grid.minor = theme_blank(),
panel.grid.major = theme_blank()
)+
geom_text(data = test,aes(x=x,y=y_pos,label=n))
p2
grid.arrange(p1, p2, heights = c(8.5, 1.5), nrow=2)
enter code here
然而,這是非常複雜,將很難修改不同的數據。理想情況下,我希望能夠以屏幕百分比傳遞Y座標。 在此先感謝!
annotation_custom()和代碼[從這裏](http://stackoverflow.com/questions/9690648/point-clipped-on-x-axis-in-ggplot)可以幫助你。見下文。 – 2012-05-02 06:43:57
請參閱下面的答案。這絕對比接受的答案簡單。 – 2016-02-17 21:28:04
ggplot2的最新版本現在內置了以下答案內置的此功能:http://stackoverflow.com/a/36036479/170352 – 2017-01-26 17:01:14