Alex
Alex

Reputation: 15708

How to display really tall ggplot?

For example, while trying to display a facetted plot with one hundred rows:

library(ggplot2)
set.seed(111)
tmp_d <- data.frame(group = rep(1:100, each = 5), 
                    x = rep(1:5, times = 100),
                    y = runif(1:500))
## looks like
#   group x         y
# 1     1 1 0.5929813
# 2     1 2 0.7264811
# 3     1 3 0.3704220
# 4     1 4 0.5149238
# 5     1 5 0.3776632
# 6     2 1 0.4183373
# ...

ggplot(tmp_d, aes(x,y)) +
    geom_point() +
    facet_wrap(~ group, ncol = 1)

I get a mess in the plotting window in Rstudio which I cannot zoom into or scroll:

enter image description here

Inconvenient work-arounds involve ggsave or knitr:

Using ggsave:

ggsave('tmp_20170104_long_ggplot.png', p, height = 100, limitsize = F)

Using knitr:

Embed the plot in a knitr code chunk with a large arbitrary value for fig.height:

---
title: "Test plot of tall ggplot2"

output:
    html_document
---

```{r, fig.height = 100}
library(ggplot2)
set.seed(111)
tmp_d <- data.frame(group = rep(1:100, each = 5), 
                    x = rep(1:5, times = 100),
                    y = runif(1:500))

ggplot(tmp_d, aes(x,y)) +
    geom_point() +
    facet_wrap(~ group, ncol = 1)
```

Two questions:

  1. How do I easily display such plots?
  2. How do I determine what the height value has to be for each of the work-arounds?

Upvotes: 1

Views: 1301

Answers (1)

baptiste
baptiste

Reputation: 77096

1- try dev.new(width=3, height=10, noRStudioGD = TRUE). If your plot is too tall for the screen, you can draw it on a pdf file an use the pdf viewer to scroll,

library(ggplot2)
set.seed(111)
tmp_d <- data.frame(group = rep(1:100, each = 5), 
                    x = rep(1:5, times = 100),
                    y = runif(1:500))

p <- ggplot(tmp_d, aes(x,y)) +
  geom_point() +
  facet_wrap(~ group, ncol = 1)

nc <- length(unique(ggplot_build(p)[["data"]][[1]][["PANEL"]]))

ggsave("tall.pdf", p, width=7, height = nc * 7 + 2, limitsize = FALSE)

enter image description here

2- if you have N rows of panels and each panel should be H inches tall, something like N x H plus some room for axes etc. should work well.

Upvotes: 5

Related Questions