gpt4 book ai didi

r 带有分数的标签图

转载 作者:行者123 更新时间:2023-12-04 05:02:52 25 4
gpt4 key购买 nike

我想创建 3 个图,每个图包含来自不同数据框的 2 条线的图,然后用特定的分数标记每个图。

例如,我有 3 个数据框:

df1 <- data.frame(x=c(1,2,3,4),y=c(2,3,4,5), z=c(3,3,6,8))
df2 <- data.frame(x=c(3,4,5,6),y=c(1,3,6,7), z=c(2,4,4,8))
df3 <- data.frame(x=c(1,2,2,3),y=c(2,5,6,9), z=c(2,5,6,7))

我想:

1) 为每个数据框创建 3 个不同的图,每个图有一条红线和一条蓝线;

2) 使用每个图的不同分数在每个图的蓝线上添加注释。

例如,数据框 1 的图是这样的:
p1 <- ggplot(data = df1) + geom_line(aes(x=x,y=y, colour="blue")) + geom_line(aes(x=x,y=z, colour="red")) +  scale_colour_manual(name="data", values=c("red", "blue"))

然后在我尝试过的蓝线上添加标签:
p1 + geom_text(aes(x=df1$x[which.max(df1$y)]+1, y = max(df1$y)+4,  label = "{\frac{23 22 22}{44 28 32}}", size=2, parse=TRUE))

但这不起作用,我已经搜索了很多小时,但找不到如何在注释中使用分数(和包含分数的括号)。任何帮助深表感谢!

最佳答案

目前还不清楚你想要什么。这是一种尝试;

  • 我用 mapply循环绘图和分数并生成绘图列表。
  • 我使用 frac(x,y) 创建分数
  • 我使用 scale_y_continuous 设置了图的限制
  • 我用 gridExtra在同一个图中排列图(可选)

  • enter image description here

    这里是完整的代码:
     ## a generic function that take a fraction ana a  data.frame as inputs
    ## it generate a plot
    plot.frac <- function(dat,frac){
    p <- ggplot(dat) +
    geom_line(aes(x=x,y=y, colour="blue")) +
    geom_line(aes(x=x,y=z, colour="red")) +
    scale_colour_manual(name="data", values=c("red", "blue"))+
    geom_text(x=dat$x[which.max(dat$y)]-0.05, y = max(dat$y)+4,
    label = frac, size=5,parse=TRUE)+
    ## Note the use of limits here to display the annotation
    scale_y_continuous(limits = c(min(dat$y), max(dat$y)+5))
    p
    }
    ## create a list of data.frame of mapply
    df.list <- list(df1,df2,df3)
    ## ggplot2 use plotmath so for fraction you use frac(x,y)
    ## here I construct the 2 terms using paste
    frac.func <- function(num,den) paste('frac("',num,'","',den,'")',sep='')
    num1 <- "line1:23 22 22"
    den1 <- "line2: 44 28 32"
    num2 <- "line1:23 50 22"
    den2 <- "line2: 44 50 32"
    num3 <- "line1:23 80 22"
    den3 <- "line2: 44 80 32"
    ## create a list of fractions for mapply

    frac.list <- list(frac.func(num1,den1),
    frac.func(num2,den2),
    frac.func(num3,den3))
    frac.list <- list(frac,frac,frac)
    ## use mapply to call the plot over the 2 lists of data.frame and fractions
    ll <- mapply(plot.frac,df.list,frac.list,SIMPLIFY=FALSE)
    library(gridExtra)
    do.call(grid.arrange,ll)

    关于r 带有分数的标签图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15911621/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com