简体   繁体   中英

ggplot2 facets: Different annotation text for each plot

I have the following generated data frame called Raw_Data:

    Time Velocity Type
1    10        1    a
2    20        2    a
3    30        3    a
4    40        4    a
5    50        5    a
6    10        2    b
7    20        4    b
8    30        6    b
9    40        8    b
10   50        9    b
11   10        3    c
12   20        6    c
13   30        9    c
14   40       11    c
15   50       13    c

I plotted this data with ggplot2:

ggplot(Raw_Data, aes(x=Time, y=Velocity))+geom_point() + facet_grid(Type ~.)

I have the objects: Regression_a, Regression_b, Regression_c. These are the linear regression equations for each plot. Each plot should display the corresponding equation.

Using annotate displays the particular equation on each plot:

annotate("text", x = 1.78, y = 5, label = Regression_a, color="black", size = 5, parse=FALSE)

I tried to overcome the issue with the following code:

Regression_a_eq <- data.frame(x = 1.78, y = 1,label = Regression_a,
                       Type = "a")
p <- x + geom_text(data = Raw_Data,label = Regression_a)

This did not solve the problem. Each plot still showed Regression_a, rather than just plot a

You can put the expressions as character values in a new dataframe with the same unique Type 's as in your data-dataframe and add them with geom_text :

regrDF <- data.frame(Type = c('a','b','c'), lbl = c('Regression_a', 'Regression_b', 'Regression_c'))

ggplot(Raw_Data, aes(x = Time, y = Velocity)) +
  geom_point() + 
  geom_text(data = regrDF, aes(x = 10, y = 10, label = lbl), hjust = 0) +
  facet_grid(Type ~.)

which gives:

在此处输入图片说明

You can replace the text values in regrDF$lbl with the appropriate expressions.

Just a supplementary for the adopted answer if we have facets in both horizontal and vertical directions.

regrDF <- data.frame(Type1 = c('a','a','b','b'),
                     Type2 = c('c','d','c','d'),
                     lbl = c('Regression_ac', 'Regression_ad', 'Regression_bc', 'Regression_bd'))    
ggplot(Raw_Data, aes(x = Time, y = Velocity)) + 
       geom_point() + 
       geom_text(data = regrDF, aes(x = 10, y = 10, label = lbl), hjust = 0) +
       facet_grid(Type1 ~ Type2)

The answer is good but still imperfect as I do not know how to incorporate math expressions and newline simultaneously ( Adding a newline in a substitute() expression ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM