How to Plot With Metricsgraphics: Exercises


Metricsgraphics is an htmlwidget interface to the MetricsGraphics.js JavaScript/D3 chart library.


Building metricsgraphics charts follows the “piping” idiom, made popular through the magrittr, ggvis and dplyr packages. This makes it possible to avoid one giant function with a ton of parameters and facilitates, breaking out the chart and building into logical steps. While MetricsGraphics.js charts may not have the flexibility of the ggplot2, you can build functional, interactive [multi-]lines, scatter-plot, bar charts, histograms and you can even link charts together.

All plots begin with the mjs_plot, which sets up the widget. You then use mjs_histograms, mjs_hist, mjs_line, mjs_bar or mjs_point to specify the “geom”” you want to use for plotting. However, unlike the ggplot2 (or even base plot), you cannot combine “geoms.” The only exception to that is adding more lines to a mjs_line plot. This is not a limitation of the package, but more a design principle of the underlying MetricsGraphics JavaScript library.

Before proceeding, please follow our short tutorial.

Look at the examples given and try to understand the logic behind them. Then, try to solve the exercises below using R without looking at the answers. Then, check the solutions to check your answers.

To begin, load these packages and data-frames:


tmp <- data.frame(year=seq(1790, 1970, 10), uspop=as.numeric(uspop))

Exercise 1

Create a basic line chart of years and US population.

Exercise 2

Add a marker named “Marker” in the year 1850.

Exercise 3

Add a baseline named “baseline” in the uspop = 150.

Exercise 4

Create a basic bar chart of the tmp data frame.

Learn more about using different visualization packages in the online course R: Complete Data Visualization Solutions. In this course, you will learn how to:

  • Work extensively with the ggplot package and its functionality
  • Learn what visualizations exist for your specific use case
  • And much more

Exercise 5

Set the width to 500 and the height to 400.

Exercise 6

Create a basic scatter-plot between wt and mpg of the mtcars data frame.

Exercise 7

Set the color and size of the data points according to gear.

Exercise 8

Add titles to “x” and “y” axes.

Exercise 9

Add square lines to the plot.

Exercise 10

Set the size according to qsec.