Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
You probably learned to make a line graph back in high school (or even middle school!). But the ggplot
R package can make these graphs come to life. Let’s take a look at how to do this.
First, we need interesting data. For this post, we will use this earth surface temperature data. This dataset is pre-processed so we can explore climate trends right off the bat. Your data may need some coaxing to get it in a form that can be plotted. But once you have the data cleaned and formatted there is so much you can do to visualize it with ggplot
.
Here let’s explore the temperature trends in Denmark. The dataset has four Danish cities: Aalborg, Aarhus, Copenhagen, and Odense. Temperatures begin in 1743 and continue through 2013.
The first call to ggplot()
defines the dataframe and assigns Year
to the x variable and AverageTemperature
to the y variable. The next call to geom_point()
creates a point for each datum. Next, the geom_line()
call adds a line between points. Here we made the line ‘steelblue’ to stand out. We use scale_x_discrete()
to display specific years on the x-axis which makes it easier to read the plot. Then facet_wrap()
makes a separate panel for each city. The last two steps are labs()
to add labels and theme()
to adjust the appearance.
require(ggplot2) line_graph <- ggplot(df_yearly, aes(x = Year, y = AverageTemperature, group = 1)) + geom_point() + geom_line(color="steelblue") + scale_x_discrete(breaks=seq(1743, 2013, 50)) + facet_wrap(~City) + labs(subtitle = "Mean Annual Temperatures", x = "Year", y = "Average Temperature") + theme_minimal() + theme(text = element_text(size = 20))
Thanks for reading and I hope this helps your R project! If there is a topic you would like me to explore, drop me a line through the contact me page.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.