Draw ggplot2 Line & Barplot in Same Graph in R (Example Code)
In this R tutorial you’ll learn how to draw a line and a barplot in the same graphic.
Preparing the Example
data(iris) # Example data iris_sum <- aggregate(. ~ Species, iris, sum) iris_sum # Species Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 setosa 250.3 171.4 73.1 12.3 # 2 versicolor 296.8 138.5 213.0 66.3 # 3 virginica 329.4 148.7 277.6 101.3 |
data(iris) # Example data iris_sum <- aggregate(. ~ Species, iris, sum) iris_sum # Species Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 setosa 250.3 171.4 73.1 12.3 # 2 versicolor 296.8 138.5 213.0 66.3 # 3 virginica 329.4 148.7 277.6 101.3
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2") |
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2")
my_plot <- ggplot(iris_sum) + # Create ggplot2 barchart geom_bar(aes(Species, Sepal.Width), stat = "identity") my_plot |
my_plot <- ggplot(iris_sum) + # Create ggplot2 barchart geom_bar(aes(Species, Sepal.Width), stat = "identity") my_plot
Example: Draw Overlaid Line on Top of ggplot2 Barplot
my_plot + # Draw line on top of barplot geom_line(aes(Species, Petal.Width, group = 1), col = "#1b98e0", lwd = 3) |
my_plot + # Draw line on top of barplot geom_line(aes(Species, Petal.Width, group = 1), col = "#1b98e0", lwd = 3)
Further Resources & Related Tutorials
Have a look at the following R tutorials. They focus on topics such as lines, colors, and ggplot2.