简体   繁体   English

ggplot2构面:每个图的注释文字不同

[英]ggplot2 facets: Different annotation text for each plot

I have the following generated data frame called Raw_Data: 我有以下生成的数据框,称为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: 我用ggplot2绘制了这些数据:

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

I have the objects: Regression_a, Regression_b, Regression_c. 我有以下对象: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 每个图仍显示Regression_a,而不仅仅是图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 : 您可以将表达式作为字符值放在具有与数据数据框中相同的唯一Type的新数据geom_text ,并使用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. 您可以使用适当的表达式替换regrDF$lbl的文本值。

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 ). 答案是好的,但仍然不完善,因为我不知道如何同时合并数学表达式和换行符( 在replace()表达式中添加换行符 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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