plot a histogram with ggplot in r

Here's an example code to plot a histogram using ggplot2 in R:

main.r
library(ggplot2)
my_data <- data.frame(x = rnorm(1000, mean = 50, sd = 10))
ggplot(data = my_data, aes(x = x)) +
  geom_histogram(binwidth = 2, color = "black", fill = "white") +
  ggtitle("Histogram of My Data") +
  xlab("X Variable Label") +
  ylab("Count")
260 chars
8 lines

In this example, we first create a data frame called my_data with a single variable x, which is a random normal distribution with a mean of 50 and a standard deviation of 10. Then we use ggplot function to specify the data frame and the aesthetics, aes(), which in this case is x (our variable of interest). Next, we add the geom_histogram() layer to create the actual histogram, which takes two arguments: binwidth sets the width of the bins in the histogram and fill specifies the fill color inside each bin. Finally, we add some labels and a title using ggtitle() and xlab() and ylab() functions.

gistlibby LogSnag