...

/

Customizing Lines with ggplot2

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 the gapminder dataset using the filter() function. The new df data frame will only include the rows where the country is either Germany or Sweden.
  • Line 2: We create a new object named chart and use the <- assignment operator for storing the graph in the chart object. We initialize a new ggplot object with the ggplot() function and pass the df data frame. Using the + operator, we add a layer to the ggplot object.
  • Lines 3–4: We use the geom_line() function to create a line chart. We used the aes() function for mapping the year variable to the x-axis and the lifeExp variable to the y-axis. We group the data by the country variable using the color argument and change the width of lines to 1 using the linewidth argument.
  • Line 5: We use the scale_color_manual() function to specify different colors for the line chart. We also use the theme_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 ...