Yang Mei Lian
Yang Mei Lian

Reputation: 75

Histogram with ggplot2: change xticks, percentage of y

I have a vector x

 x = sample (1:3000, 20000, replace = T)

I tried to plot histogram of x

ggplot() + aes(x)+ geom_histogram() + scale_x_log10() + geom_bar(aes(y = (..count..)/sum(..count..))) + scale_y_continuous(labels = scales::percent)

enter image description here

I have two problems:

  1. Why does the y axis showed 200%, 400%; it is impossible for a histogram.

  2. How can I customize the x-ticks values. I want to display x-ticks as 0, 1, 2 ... 10, 20, 30 ... 10, 100.

Thanks a lot

Upvotes: 1

Views: 4574

Answers (1)

Alex
Alex

Reputation: 4995

I cleaned your code a bit. You included one geom_histogram() too much. Because of that the wired y-axis. The ticks you can control within the breaks argument of the scale functions.

Try this:

df <- data.frame(x = sample (1:3000, 20000, replace = T))

ggplot(df, aes(x = x)) + 
geom_histogram(aes(y = (..count..)/sum(..count..)))  +
scale_y_continuous(labels = scales::percent) +
scale_x_log10(breaks=c(1,100,1000)) 

enter image description here

Upvotes: 2

Related Questions