0

I have this plot

ggplot(data, aes(D3)) + 
geom_histogram(aes(fill=(..count..)/sum(..count..)), stat = "count", na.rm = TRUE, binwidth =1) +
geom_text(aes(y = ((..count..)), label = scales::percent( (..count..)/sum(..count..)) ), stat = "count", vjust = -0.25) +
scale_fill_gradient("", low = "green", high = "red")

which outputs a this nice histogram enter image description here

as you can see y axis shows count instead of percentage.

On other hand if I switch to

ggplot(data, aes(D3)) + 
    geom_histogram(aes(y = (..density..)), binwidth = 1) + 
    geom_text(aes( label = format(100*..density.., digits=1,), y= ..density.. ), stat= "bin", binwidth =1, vjust = -0.2 ) + 
    scale_y_continuous(labels = scales::percent)

it outputs this (quite ugly) plot with zeroes on the y axis

enter image description here

How can I adjust y-axis on first plot, ie show percentage instead count? or remove those zeroes in the second?

rmorelli74
  • 46
  • 4
  • 1
    This is easy enough to help with, using some `dplyr` or other functions, if you make a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – camille Nov 21 '18 at 13:19
  • @camille well, I know how to deal with this using `dplyr` and calculating percentage before going through ggplot but I am working with young students (17yr) and would like to keep it simple as possible using `..count..` without using `dplyr`. – rmorelli74 Nov 21 '18 at 13:45
  • It's a little hard to tell without an example dataset, but my guess is you want `y = stat(count/sum(count))` inside `aes()` in both `geom_histogram()` and `geom_text()`. Then you can add `scale_y_continuous(labels = scales::percent)`. (The `stat()` code was introduced as the replacement for the `..` names starting in **ggplot2** version 3.0.0.) – aosmith Nov 21 '18 at 19:48
  • @aosmith `dt <- as.data.frame(rnorm(500, 2000)) ` `colnames(dt) <- "D3"` `dt$D3 <- as.integer(dt$D3)` `ggplot(dt, aes(D3)) + geom_histogram(aes(fill=(..count..)/sum(..count..)), stat = "count", na.rm = TRUE, binwidth =1) + geom_text(aes(y = ((..count..)), label = scales::percent( (..count..)/sum(..count..)) ), stat = "count", vjust = -0.25) + scale_fill_gradient("", low = "green", high = "red")` – rmorelli74 Nov 22 '18 at 07:26
  • You can go ahead and edit your question to add your dataset (don't forget to set your seed so it is reproducible!). Did you try what I suggested? I'm pretty sure it does what you want now that I see your example dataset. – aosmith Nov 23 '18 at 18:04

0 Answers0