...

/

Customizing Fonts and Colors with ggplot2

Customizing Fonts and Colors with ggplot2

Learn how to customize the fonts and colors of ggplot2 charts.

Customizing fonts and colors

After building a data visualization, the next step can be customization. We can customize the font and colors of various plot elements in ggplot2 to effectively communicate our data and enhance the aesthetic appeal of the plot using the theme() function.

Using the element_text() function inside the theme() function, we can customize the font, font family, and color of plot elements such as the title, subtitle, caption, and tag.

Let’s first create a simple pie chart using the housing dataset from the MASS package. We’ll also add a title, subtitle, caption, and tag to the plot and save it in an object named chart. Then, we’ll customize this plot.

Press + to interact
chart<-ggplot(housing) +
geom_col(aes(x = "", y = Freq, fill =Type)) +
coord_polar(theta = "y")+
theme_bw()+
scale_fill_manual(values = c("#0b7a75","#1DD3B0","#5DA9E9","#03045E"))+
labs(title = "Distribution of Housing Types",
subtitle = "Pie chart showing different types of housing",
caption = "Source: housing (MASS package)",
tag = "Figure 1")
chart
  • Line 1: 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 housing dataset. Using the + operator, we add a layer to the ggplot object.
  • Line 2: We use the geom_col() function to create a bar chart where the height of each bar is determined by the Freq variable and the fill color is determined by the Type variable.
  • Line 3: Next, we use the coord_polar() function to add a polar coordinate layer to the plot. With this function, the height of the bars is converted into angles around the center of the plot. We also set the theta argument to "y", because of which the angles will be proportional to the values on the y-axis.
...
Access this course and 1400+ top-rated courses and projects.