2

Using the code below, I'm generating a set of simple histogram:

data(mtcars); Vectorize(require)(package = c("ggplot2", "ggthemes", "dplyr"))
mtcars %>% 
    add_rownames(var = "model") %>% 
    gather(var, value, -model, -am) %>% 
    filter(var %in% c("hp")) %>% 
    # Define chart
    ggplot(aes(value)) +
    geom_histogram(aes(y = ..ncount..), colour = "black", fill = "gray58",
                   binwidth = 15) +
    geom_density(aes(y = ..scaled..), colour = "red") +
    facet_wrap( ~am, ncol = 3, scales = "free") 

First attempt

I would like to maintain scale that is produced when generating a histogram without the ..ncount.. special variable, as in the example:

mtcars %>% 
    add_rownames(var = "model") %>% 
    gather(var, value, -model, -am) %>% 
    filter(var %in% c("hp")) %>% 
    # Define chart
    ggplot(aes(value)) +
    geom_histogram(colour = "black", fill = "gray58",
                   binwidth = 15) +
    geom_density(aes(y = ..scaled..), colour = "red") +
    facet_wrap( ~am, ncol = 3, scales = "free") 

poor geom_density

But it makes the geom_density look poor.

Task

So what I want boils down to:

  • keep scale of y axis from the second one
  • keep graphics from the first one
Konrad
  • 17,740
  • 16
  • 106
  • 167
  • @SandyMuspratt I had a look at the linked post. I don't know how to achieve the final outcome where I can take scale from the *second* chart and graphs from *first* one. With respect to the graphs, I'm satisfied with the first chart but I want scale from the second. – Konrad Dec 17 '15 at 21:04
  • 1
    My vote goes for calling `hist` in advance, and then `scale_y_continuous(breaks = 0:nmax/nmax, labels = 0:nmax)`. – tonytonov Dec 18 '15 at 15:21
  • @tonytonov I will have a look, thanks for the suggestion. I understand that you also suggest to leave `y = ..ncount..` for the `geom_hist`? – Konrad Dec 18 '15 at 16:12
  • 1
    Yes, either that or (even better) `geom_bar(..., stat = "identity")` on the precomputed histogram, so you won't do the same thing twice. – tonytonov Dec 18 '15 at 16:27
  • OK, I will play with it. Following [this post](http://stackoverflow.com/a/14570974/1655567) I reckon that it would be actually useful to access a special variable pertaining to the value *before* transformation. – Konrad Dec 18 '15 at 16:30

0 Answers0