plot a distribution in r

To plot a distribution in R, you can use the ggplot2 package, which provides an easy and flexible way to create plots. Here's an example of how to plot a normal distribution using ggplot2:

main.r
# Generate some random normally distributed data
set.seed(123)
data <- rnorm(1000)

# Load ggplot2 library
library(ggplot2)

# Create a data frame with the data
df <- data.frame(x = data)

# Create the plot
ggplot(df, aes(x = x)) +
  geom_histogram(binwidth=0.2, color="white", fill = "skyblue", alpha = 0.7) +
  stat_function(fun = dnorm, args = list(mean = mean(data), sd = sd(data)), color = "red", lwd = 2)
411 chars
15 lines

This code will create a histogram of the data with a density curve overlaid on top, representing the normal distribution with the same mean and standard deviation as the data.

You can adjust the binwidth of the histogram to change the level of granularity, and also adjust the parameters of the normal distribution.

gistlibby LogSnag