Customizing Legends and Margins with ggplot2
Learn how to customize plot legends and margins in ggplot2.
We'll cover the following...
Legends in ggplot2
In ggplot2
, the legend is an essential aspect of a graph as it helps to identify the different elements of the plot. Legends get automatically generated when we map variables to different attributes. We can customize the legends using the theme()
function. By default, the legend is displayed on the right side of the plot, but it can be customized to be placed in different positions or to have a specific appearance.
Let’s first create an area chart using the gapminder
dataset from the gapminder
package. We’ll then customize the legends and margins on our graph.
Press + to interact
df <- gapminder %>%filter(country %in% c("Germany", "Sweden","Italy"))chart <- ggplot(df)+geom_area(aes(x = year, y = gdpPercap, fill = country))+theme_bw()+scale_fill_manual(values = c("#1DD3B0","#5DA9E9","#03045E"))chart
- Lines 1–2: 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 isGermany
,Sweden
, andItaly
. - Line 3: 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. - Line 4: We use the
geom_area()
function to create an area chart where we use theaes()
function for mapping theyear
variable to the x-axis andgdpPercap
variable to the y-axis. We also group the data by thecountry
variable using thecolor
argument. - Line 5: We use the
theme_bw()
function for changing the default gray theme to a black and white theme. - Line 6: We use the
scale_color_manual()
function to specify different colors for the area chart.
The chart above shows that the default ...
Access this course and 1400+ top-rated courses and projects.