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
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

r graph figure 1 draw ggplot2 line barplot same graph r

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)

r graph figure 2 draw ggplot2 line barplot same graph r

Further Resources & Related Tutorials

Have a look at the following R tutorials. They focus on topics such as lines, colors, and ggplot2.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top