ggplot facets:在选定的facet

时间:2017-12-05 17:14:19

标签: r ggplot2 facet annotate geom-text

我想创建一个2 x 2面刻图,其中四个面共享一条垂直线。但是,因为顶部的构面与底部的构面具有相​​同的日期信息,所以我只希望对vline进行两次注释:在这种情况下,在底部的两个构面中。

我看了一眼。 here,这对我不起作用。 (此外,我怀疑今天这是否仍然是有效的代码。)我也看了here。我还查看了如何影响geom_text中的字体大小:根据帮助页面size。在下面的情况下,它不是很好。

这是我的代码:

library(ggplot2)
library(tidyr)

my_df <- read.table(header = TRUE, text = 
                      "Date AM_PM First_Second Systolic Diastolic Pulse 
                    01/12/2017 AM 1 134 83 68 
                    01/12/2017 PM 1 129 84 76
                    02/12/2017 AM 1 144 88 56
                    02/12/2017 AM 2 148 93 65
                    02/12/2017 PM 1 131 85 59
                    02/12/2017 PM 2 129 83 58
                    03/12/2017 AM 1 153 90 62
                    03/12/2017 AM 2 143 92 59
                    03/12/2017 PM 1 139 89 56
                    03/12/2017 PM 2 141 86 56
                    04/12/2017 AM 1 140 87 58
                    04/12/2017 AM 2 135 85 55
                    04/12/2017 PM 1 140 89 67
                    04/12/2017 PM 2 128 88 69
                    05/12/2017 AM 1 134 99 67
                    05/12/2017 AM 2 128 90 63
                    05/12/2017 PM 1 136 88 63
                    05/12/2017 PM 2 123 83 61
                    ")

# setting the classes right
my_df$Date <- as.Date(as.character(my_df$Date), format = "%d/%m/%Y")
my_df$First_Second <- as.factor(my_df$First_Second)

# to tidy format
my_df2 <- gather(data = my_df, key = Measure, value = Value, 
                  -c(Date, AM_PM, First_Second), factor_key = TRUE)

# Measures in 1 facet, facets split over AM_PM and First_Second
## add anntotations column for geom_text
my_df2$Annotations <- rep("", 54)
my_df2$Annotations[c(4,6)] <- "Start"

p2 <- ggplot(data = my_df2) +
  ggtitle("Blood Pressure and Pulse as a function of AM/PM,\n Repetition, and date") +
  geom_line(aes(x = Date, y = Value, col= Measure, group = Measure), size = 1.)  +
  geom_point(aes(x = Date, y = Value, col= Measure, group = Measure), size= 1.5) +
  facet_grid(First_Second ~ AM_PM) +
  geom_vline(aes(xintercept = as.Date("2017/12/02")), linetype = "dashed", 
             colour = "darkgray") + 
  theme(axis.text.x=element_text(angle = -90)) 

p2

产生此图表: enter image description here

这是我开始的基本情节。现在我们尝试对其进行注释。

p2 + annotate(geom="text", x = as.Date("2017/12/02"), y= 110, label="start", size= 3) 

产生这个情节:

enter image description here

此图存在注释发生4次的问题,而我们只想在图的底部发生。

现在我们使用geom_text,它将使用数据框中的“注释”列,与this SO Question一致。注意,第一次创建“p2”时,添加到数据框中的列必须存在(这就是我们在上面添加列的原因)

p2 + geom_text(aes(x=as.Date("2017/12/02"), y=100, label = Annotations, size = .6))

产生这个情节:

enter image description here

是的,我们成功地仅在图表的底部两部分中获取注释。但是字体太大了(......而且丑陋)当我们尝试用size来纠正它时,有两件事情很有趣:(1)字体大小没有改变(虽然你会期望从帮助中找到它)页面)和(2)添加了一个图例。

我一直在点击很多,并且几小时后都无法解决这个问题。任何帮助将不胜感激。

0 个答案:

没有答案