【问题标题】:Good geom_text quality in multiple facet_grid in ggplot2 with regression equations具有回归方程的 ggplot2 中的多个 facet_grid 中的 geom_text 质量良好
【发布时间】:2016-11-30 00:18:54
【问题描述】:

我想使用 ggplot2 在不同方面绘制多个回归方程...我想我成功了,感谢this post

但 geom_text 字体很难看,因为它在同一个文本区域中多次复制相同的字母:

iris <- iris
iris2 <- data.frame(iris, family = c(rep(rep(1:2,25),3)))
iris3 <- data.frame(iris2, group = paste(iris2$Species, iris2$family, sep = "_"))

intercept <- ddply(iris3, .(group), function(x)  coefficients(lm(Petal.Length~Petal.Width,x)))
rcarre <- ddply(iris3, .(group), function(x) summary(lm(Petal.Length~Petal.Width,x))$r.squared) 

names(rcarre) <- c("group", "R2") 
names(intercept) <- c("group", "intercept", "slope") 
coefs <- merge(intercept, rcarre) 
coefs <- data.frame(coefs,
                eq = paste("Y=",round(coefs$intercept,2),"+",round(coefs$slope, 2),"x",", ","R2=",round(coefs$R2,2), sep = ""))
coefs$eq = as.character(coefs$eq)

iris4 <- merge(iris3, coefs)

ggplot(iris4, aes(x = Petal.Width, y = Petal.Length, colour = Species)) +
  geom_point() +
  geom_smooth(method=lm, se=F) +
  facet_grid(family~Species) +
  geom_text(aes(label=eq, x=1.5, y=6)) +
  theme_linedraw() 

我尝试使用给定的解决方案here,但它对我不起作用

ggplot(iris4, aes(x = Petal.Width, y = Petal.Length, colour = Species)) +
  geom_point() +
  geom_smooth(method=lm, se=F) +
  facet_grid(family~Species) +
  geom_text(aes(label=iris4$eq, x=1.5, y=6), data = data.frame()) +
  theme_linedraw() 

使用annotate,我有一个错误消息(我理解问题但我无法解决它)

ggplot(iris4, aes(x = Petal.Width, y = Petal.Length, colour = Species)) +
  geom_point() +
  geom_smooth(method=lm, se=F) +
  facet_grid(family~Species) +
  annotate("text", x = 1.5, y = 6, label = iris4$eq) +
  theme_linedraw() 

如果我参考 coefs 表(与刻面长度相同),则方程不再匹配

ggplot(iris4, aes(x = Petal.Width, y = Petal.Length, colour = Species)) +
  geom_point() +
  geom_smooth(method=lm, se=F) +
  facet_grid(family~Species) +
  annotate("text", x = 1.5, y = 6, label = coefs$eq) +
  theme_linedraw() 

有人有解决办法吗?

非常感谢!

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    问题是 ggplot 正在打印数据中每一行的文本。您可以通过只为每个标签提供一行来阻止这种情况。在这里,我使用dplyr::distinct 执行此操作,但还有其他方法

    ggplot(iris4, aes(x = Petal.Width, y = Petal.Length, colour = Species)) +
      geom_point() +
      geom_smooth(method=lm, se=F) +
      facet_grid(family~Species) +
      geom_text(aes(label=eq, x=1.5, y=6), data = dplyr::distinct(iris4, eq, .keep_all = TRUE)) +
      theme_linedraw() 
    

    【讨论】:

    • 问题是 ggplot 正在打印数据中每一行的文本:我知道这一点(我在其他帖子上读过),但我找不到解决这个问题的方法...您的答案正是我所需要的!非常感谢@RichardTelford
    猜你喜欢
    • 2013-03-29
    • 2015-03-25
    • 2018-01-07
    • 2012-12-18
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    相关资源
    最近更新 更多