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
R
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
chartand use the<-assignment operator for storing the graph in thechartobject. We initialize a newggplotobject with theggplot()function and pass thehousingdataset. Using the+operator, we add a layer to theggplotobject. - Line 2: We use the
geom_col()function to create a bar chart where the height of each bar is determined by theFreqvariable and the fill color is determined by theTypevariable. - 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 thethetaargument to"y", because of which the angles will be proportional to the values on the y-axis. - Lines 4–5: We apply the
Ask