1

enter image description hereI have generate 1000 set of random data for Poisson Distribution and plot all the data into a probability distribution graph. I would like to change the x-axis scale as 2 per unit like 0,2,4,6,8,10....I have set the max and min value of x-axis but it didn't show what I expect

set.seed(124)

Sample1000 <- replicate(1000, matrix(data=rpois(100, lambda = 3),ncol = 1), simplify = TRUE)
Graph1000 <- gather(as.data.frame(Sample1000))
View(Sample1000)
colMeans(Sample1000)
apply(Sample1000, 2, var)

ggplot(Graph1000, aes(x = value)) +
  geom_density(aes(group = key)) +
  labs(x = "y", y = "P(y)", title = "Probability density function for 1000 sample") +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(expand = c(0,0), limits = c(0,14))  +
  scale_y_continuous(expand = c(0,0))
Kok Lin
  • 39
  • 6
  • 2
    Add a `breaks` argument that covers the range of the data. For example `scale_x_continuous(expand=c(0,0), breaks=seq(0, 20, 2))`. If you want to set limits that are smaller than the range of the data, use `coord_cartesian(xlim=c(0,14))`. Setting the limits within `scale_x_continuous` will *exclude* data outside the limits from any calculations (such as the kernel density estimate). – eipi10 Jun 26 '19 at 15:21
  • For more on `coord_cartesian` vs. `scale_x/y_continuous` [see here](https://stackoverflow.com/q/32505298/496488). – eipi10 Jun 26 '19 at 15:27
  • but the largest number I get from random generate is 12 so that's why i set my limit for scale_x_continuous as (0,14) – Kok Lin Jun 26 '19 at 15:45

1 Answers1

0

You can set the breaks on scale_x_continuous().
Here is the code that produce your plot:

ggplot(Graph1000, aes(x = value)) +
  geom_density(aes(group = key)) +
  labs(x = "y", y = "P(y)", title = "Probability density function for 1000 sample") +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5)) +
  #Set breaks on x axis
  scale_x_continuous(breaks = seq(from = 0,to = 14,by = 2), limits = c(0,14))  +
  scale_y_continuous(expand = c(0,0))
vpz
  • 984
  • 1
  • 15
  • 26