Skip to content

Plotting only highest R squared panels #37

@ggrothendieck

Description

@ggrothendieck

Is it possible to plot only the highest R squared panels in lattice without preprocessing the data to remove them? In aphalo/ggpmisc#46 it is suggested that it is not possible in ggplot2 so I thought I would ask regarding lattice. Below are examples of doing it with preprocessing using lattice/latticeExtra and using tidyverse/ggplot2.

library(latticeExtra)

# all trees except 4 have R squared >= 0.97
is.highR2 <- function(tree)
  summary(lm(age ~ circumference, Orange, subset = Tree == tree))$r.squared >= 0.97
Trees <- Filter(is.highR2, levels(Orange$Tree)); Trees
## [1] "3" "1" "5" "2"

if (length(Trees)) {
  p1 <- xyplot(age ~ circumference | Tree, Orange, subset = Tree %in% Trees) + 
    layer(panel.ablineq(lm(y ~ x), r.squared = TRUE, label = "", sep = "", adj = c(0.75, -4))) 
  plot(p1)
}

##################################################################

library(broom)
library(dplyr)
library(ggplot2)
library(ggpmisc)

# all Trees except 4 have R squared >= 0.97
Trees <- Orange %>%
  nest_by(Tree) %>%
  summarize(model = list(lm(age ~ circumference, data)), glance(model)) %>%
  filter(r.squared >= 0.97) %>%
  pull(Tree)

# plot
if (length(Trees)) {
  p2 <- Orange %>%
    filter(Tree %in% Trees) %>%
    ggplot(aes(circumference, age)) +
      geom_point() +
      stat_poly_eq() +
      geom_smooth(method = "lm", se = FALSE) +
      facet_wrap(~ Tree)
  plot(p2)
 } 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions