make a pretty histogram with ggplot2 in r

To make a pretty histogram with ggplot2 in r, first we need some data to work with. Let's use the mpg dataset from ggplot2 package.

main.r
library(ggplot2)

# Load the data
data(mpg)

# Create histogram with default setting
ggplot(mpg, aes(x = cty)) +
  geom_histogram()
132 chars
9 lines

This will generate a basic histogram, but it's not very pretty. We can improve the appearance of the plot by tweaking the parameters and adding a theme.

main.r
# Create a pretty histogram
ggplot(mpg, aes(x = cty)) +
  geom_histogram(fill = "lightblue", color = "grey50") +
  labs(title = "City Miles per Gallon", x = "Miles per Gallon", y = "Count") +
  theme_minimal()
210 chars
6 lines

Here, we customized the plot by specifying the fill and color of the bars, adding a title and axis labels, and applying a theme. In this case, we use theme_minimal() to remove the background grid and other default formatting, but you can choose from several built-in themes or create your own.

This should give us a pretty histogram that showcases our data effectively.

gistlibby LogSnag