Skip to content

Plotting confidence intervals with ggplot, in multiple facets.

8 messages · Jeff Newmiller, Rui Barradas, Rolf Turner +2 more

#
I have need of creating a plot displaying confidence intervals
(for the mean bias in parameter estimates) with one panel or facet
for each of the two parameters in question.

I can do this in base R graphics, but the result is not as
aesthetically pleasing as I would like.  I have attached an example
graphic in the file "eg.pdf".

I would like to try using ggplot2, but cannot get my head around the
syntax.  (Life is a struggle when one is old and senile!)  I have been
shown in the past how to produce a single-facet plot of such confidence
intervals, basically using the geom_errorbar() function, but I cannot
see how to produce multiple facets, depending on a "param" factor.  I
have thrashed around a bit but after succeeding in only confusing
myself, I thought I would save wear and tear on my brain by asking this
list.  I'm sure the answer is pretty simple, but I'm just too stupid to
see it.

Can anyone give me a recipe for creating, with ggplot(), a graphic like
unto that shown in "eg.pdf", but prettier?  I have attached the data
that were used to create "eg.pdf" in the form of a data frame, in a
file called "egData.txt".  This file was produced by dput() so read it
in using dget("egData.txt").

With eternal gratitude.

cheers,

Rolf Turner
#
ggplot(dta,aes(x=Ndat,y=estimate, ymin=lower,ymax=upper))+
  geom_point() +
  geom_errorbar(width=30) +
  facet_grid(param~1) +
  theme_minimal()

Width parameter seems odd... play with it I suppose.

For facets, you can also use facet_wrap(~param, ncol=1).

ggplot is very much about the data and the aes mapping... the more you try to manually tweak it the more messed up it tends to get.
On July 17, 2021 11:17:06 PM PDT, Rolf Turner <r.turner at auckland.ac.nz> wrote:

  
    
#
Hello,

Something like this?

library(ggplot2)

eg <- dget("data/egData.txt")

ggplot(eg, aes(Ndat, estimate)) +
 ? geom_errorbar(aes(ymin = lower, ymax = upper), width = 20) +
 ? geom_point(colour = "slateblue", size = 1) +
 ? geom_hline(yintercept = 0, colour = "red") +
 ? facet_grid(param ~ .) +
 ? theme_bw()


Hope this helps,

Rui Barradas

?s 07:17 de 18/07/2021, Rolf Turner escreveu:

  
    
#
Rolf,

Your example shows two plots with one above the other.

If that is what you want, then a solution like the one  Jeff provided  using
facet_grid() to separate data based on the parameter value. It also scales
up if you add additional sets of data for gamma and delta up to a point.

An alternative to consider if your ggplot wizardry has not kicked in, or if
your need is to connect more diverse plots into a sort of collage, is to
make multiple plots and save them as in:

P1 <- ggplot(...) ...
P2 <- ggplot(...) ...

Each of these two or more plots can operate on whatever data you supply it.
In your case, you would filter the rows that have the values you want.

Then you can use one of many packages out there such as cowplot or gridextra
to consolidate the parts as in:

plot_grid(P1, P2)

Or 

grid.arrange (P1, P2)

These other functions vary in functionality but many allow you to adjust how
many rows or columns you want or the relative sizes of the subplots and so
on. Some allow you to create output into things like a PDF where parts spill
over well into additional pages.

I note one think Jeff did not replicate. If you want that in your output,
use geom_hline as shown below:

ggplot(dta,aes(x=Ndat,y=estimate, ymin=lower,ymax=upper))+
  geom_point() +
  geom_errorbar(width=30) +
  geom_hline(yintercept = 0, color="red") +
  facet_grid(param~1)

Personally, I sometimes adjust the limits to make a graph truly start at
zero but in your case you can have error bars being displayed with parts
below zero so showing where zero is graphically can be useful.




-----Original Message-----
From: R-help <r-help-bounces at r-project.org> On Behalf Of Rolf Turner
Sent: Sunday, July 18, 2021 2:17 AM
To: r-help at r-project.org
Subject: [R] Plotting confidence intervals with ggplot, in multiple facets.



I have need of creating a plot displaying confidence intervals (for the mean
bias in parameter estimates) with one panel or facet for each of the two
parameters in question.

I can do this in base R graphics, but the result is not as aesthetically
pleasing as I would like.  I have attached an example graphic in the file
"eg.pdf".

I would like to try using ggplot2, but cannot get my head around the syntax.
(Life is a struggle when one is old and senile!)  I have been shown in the
past how to produce a single-facet plot of such confidence intervals,
basically using the geom_errorbar() function, but I cannot see how to
produce multiple facets, depending on a "param" factor.  I have thrashed
around a bit but after succeeding in only confusing myself, I thought I
would save wear and tear on my brain by asking this list.  I'm sure the
answer is pretty simple, but I'm just too stupid to see it.

Can anyone give me a recipe for creating, with ggplot(), a graphic like unto
that shown in "eg.pdf", but prettier?  I have attached the data that were
used to create "eg.pdf" in the form of a data frame, in a file called
"egData.txt".  This file was produced by dput() so read it in using
dget("egData.txt").

With eternal gratitude.

cheers,

Rolf Turner

--
Honorary Research Fellow
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276
1 day later
#
Thanks to Jeff Newmiller, Rui Barradas and Avi Gross for their
extremely helpful replies.  I have got both Jeff's and Rui's code to
run.  I am currently experimenting with Avi's suggestion of producing
multiple plots and then putting them together using plotgrid() or
grid.arrange().  This idea seems to me to be most promising in terms of
a desideratum that the y-axis scales/limits should be different on the
two facets.  Also the y-axis labels.

And speaking of y-axis labels:  is it possible in ggplot() to get
mathematical notation in axis labels, titles and possibly other
annotation?  (In the manner of plotmath() in base R graphics.)
Specifically I'd like to get the Greek letters alpha and beta in the
y-axis labels.  In base R graphics I'd do something like
ylab=expression(paste("bias in ",beta)) .  Is there an appropriate
analogue in ggplot()?  (I think that I may have asked this question
before, some time back, but have forgotten the answer.)

cheers,

Rolf

P.S.  The following is kind of apropos of nothing, but it might serve as
a useful warning to others of a Trap for Young Players.  I nearly went
mad (madder?) for a very long time when trying to get Rui's code to run.
I kept getting errors of the form:
Took me an unconscionably long while to figure out what was going on.
I could not see why Jeff's code ran without problem, while Rui's (which
was very similar) fell over.  Turns out the second character in the
offending line is a non-printing character, the 160th member of the
ASCII character set. (It can be produced using "\u00A0".)  Apparently
this is a "non-breaking space". Whatever that means.  It does NOT get
treated as white space in the usual way, and triggers the foregoing
error.

Presumably this invisible character got introduced, into the code that
Rui emailed, by one of the (many!) infuriating idiosyncrasies of
Windoze.  Yet another reason, among the many millions of such, not to
use Windoze.

R.
#
ggplot2::labs() interprets expressions as plotmath.  E.g.,

   data.frame(X=1:10,Y=(1:10)^2) %>% ggplot(aes(X,Y)) + geom_point() +
       labs(x = expression(beta), y = expression(beta^2))

-Bill
On Mon, Jul 19, 2021 at 4:24 PM Rolf Turner <r.turner at auckland.ac.nz> wrote:

            

  
  
#
Rolf,

 

Your questions probably should go to a group focused on the ggplot package, not a general R group where many do not use it.

 

A little judicious searching like "R ggplot use greek letters in text" gets you some pointers that show how to do much more than Greek letters but more complex mathematical style equations and that many aspects of ggplot support it and you can use other functions like paste() to put more complex expressions together.

 

Similarly, your comments about wanting to have different scales showing in multiple plots using facet_grid() or perhaps facet_wrap() might answer your question as the manual page explains:

 


scales

Are scales shared across all facets (the default, "fixed"), or do they vary across rows ("free_x"), columns ("free_y"), or both rows and columns ("free")?

So alter the line you use at the end to include a comma at the end of the arguments followed by ?scale=?? as needed.

 

But yes, truly independent graphs placed in a grid, after loading the packages needed, gives even more options.

 

There are some very decent books and tutorials on many aspects of ggplot including some that are free and on-line. Here is an earlier edition of one:

 

https://ggplot2-book.org/

 

Note especially this section on faceting:

 

https://ggplot2-book.org/facet.html

 

I will now go silent on ggplot-related questions ?

 

 

-----Original Message-----
From: R-help <r-help-bounces at r-project.org> On Behalf Of Rolf Turner
Sent: Monday, July 19, 2021 7:24 PM
To: r-help at r-project.org
Subject: Re: [R] Plotting confidence intervals with ggplot, in multiple facets.

 

 

 

Thanks to Jeff Newmiller, Rui Barradas and Avi Gross for their extremely helpful replies.  I have got both Jeff's and Rui's code to run.  I am currently experimenting with Avi's suggestion of producing multiple plots and then putting them together using plotgrid() or grid.arrange().  This idea seems to me to be most promising in terms of a desideratum that the y-axis scales/limits should be different on the two facets.  Also the y-axis labels.

 

And speaking of y-axis labels:  is it possible in ggplot() to get mathematical notation in axis labels, titles and possibly other annotation?  (In the manner of plotmath() in base R graphics.) Specifically I'd like to get the Greek letters alpha and beta in the y-axis labels.  In base R graphics I'd do something like ylab=expression(paste("bias in ",beta)) .  Is there an appropriate analogue in ggplot()?  (I think that I may have asked this question before, some time back, but have forgotten the answer.)

 

cheers,

 

Rolf

 

P.S.  The following is kind of apropos of nothing, but it might serve as a useful warning to others of a Trap for Young Players.  I nearly went mad (madder?) for a very long time when trying to get Rui's code to run.

I kept getting errors of the form:
Took me an unconscionably long while to figure out what was going on.

I could not see why Jeff's code ran without problem, while Rui's (which was very similar) fell over.  Turns out the second character in the offending line is a non-printing character, the 160th member of the ASCII character set. (It can be produced using "\u00A0".)  Apparently this is a "non-breaking space". Whatever that means.  It does NOT get treated as white space in the usual way, and triggers the foregoing error.

 

Presumably this invisible character got introduced, into the code that Rui emailed, by one of the (many!) infuriating idiosyncrasies of Windoze.  Yet another reason, among the many millions of such, not to use Windoze.

 

R.

 

--

Honorary Research Fellow

Department of Statistics

University of Auckland

Phone: +64-9-373-7599 ext. 88276

 

______________________________________________

 <mailto:R-help at r-project.org> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see  <https://stat.ethz.ch/mailman/listinfo/r-help> https://stat.ethz.ch/mailman/listinfo/r-help

PLEASE do read the posting guide  <http://www.R-project.org/posting-guide.html> http://www.R-project.org/posting-guide.html

and provide commented, minimal, self-contained, reproducible code.
#
Thanks to Bill Dunlap and Avi Gross for their clear and helpful answers
to my questions.

cheers,

Rolf Turner