Customizing Lines with ggplot2
Learn how to customize plot lines using settings for modifying the axis lines, grid lines, and axis ticks in ggplot2.
Introduction to lines customization
It is possible to customize all the lines that are not a direct part of the plotted data, such as grid lines, axis lines, and others, using the element_line()
function. Combining this function with the theme()
function makes it possible to modify the appearance of lines like the x-axis and y-axis.
In general, the element_line()
function allows us to change three sets of lines in a plot:
- The x-axis and y-axis lines
- Tick lines on the x-axis and y-axis
- Major and minor grid lines that run along both the x-axis and y-axis
Let’s first create a line chart with time series data using the gapminder
dataset from the gapminder
package, and then we’ll customize the chart.
Press + to interact
df <- gapminder %>% filter(country %in% c("Germany", "Sweden"))chart <- ggplot(df)+geom_line(aes(x = year, y = lifeExp, color = country),linewidth=1) +scale_color_manual(values = c("#0b7a75","#1DD3B0")) + theme_bw()chart
- Line 1: We create a new
df
data frame and store the filtered data of thegapminder
dataset using thefilter()
function. The newdf
data frame will only include the rows where the country is eitherGermany
orSweden
. - Line 2: We create a new object named
chart
and use the<-
assignment operator for storing the graph in thechart
object. We initialize a newggplot
object with theggplot()
function and pass thedf
data frame. Using the+
operator, we add a layer to theggplot
object. - Lines 3–4: We use the
geom_line()
function to create a line chart. We used theaes()
function for mapping theyear
variable to the x-axis and thelifeExp
variable to the y-axis. We group the data by thecountry
variable using thecolor
argument and change the width of lines to1
using thelinewidth
argument. - Line 5: We use the
scale_color_manual()
function to specify different colors for the line chart. We also use thetheme_bw()
function to change the default gray theme to a black and white theme.
Axis lines in ggplot2
The ggplot2
package doesn’t include axis lines by default in the plot. We can use the axis.line
...