Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: geom_pointrange() facet_grid() with coord_flip() and free scales

Tags:

r

ggplot2

I am trying to generate a graph with the estimates and confidence intervals from the same regression for a number of countries. I ran the regressions using dplyr's group_by(country), and then I aggregated all the results into a data frame with broom's tidy().

When creating the graph from this data frame (called bycountry1), I run the following code:

ggplot(bycountry1, aes(x = country, y = estimate, ymin = estimate - std.error * 2, ymax = estimate + std.error * 2)) + 
   geom_hline(yintercept = 0, colour = "black", lty = 2) +
   geom_pointrange() + 
   coord_flip() + facet_grid(. ~ term, scales = "free")

here is the graph I get

This is what I want, except that I'd like to have the scales for each box to be different, so that all of them would look more like the religious1box. Since that is the one with most variability, it dominates the scale, and then in most of the other boxes you cannot see the variance. As the code above shows, I did indicate scales = "free" in facet_grid() and I tried all the variants, also with facet_wrap(), and I cannot get this to work.

like image 233
Oriol Mirosa Avatar asked Oct 19 '22 18:10

Oriol Mirosa


1 Answers

Following the suggestion of aosmith, I made it work using geom_errorbarh and removing coord_flip(). I also had to set the height of the geom_errorbarh to 0 and add a geom_point for the estimate. Here is the code:

ggplot(bycountry1, aes(y = country, x = estimate, xmin = estimate - std.error * 2, xmax = estimate + std.error * 2)) + 
  geom_vline(xintercept = 0, colour = "black", lty = 2) +
  geom_point() + 
  geom_errorbarh(height = 0) + 
  facet_grid(. ~ term, scales = "free")

And the resulting image

enter image description here

like image 142
Oriol Mirosa Avatar answered Oct 21 '22 15:10

Oriol Mirosa