Open In App

Google Chart Overlays using googleVis package in R

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Google Chart Overlays is one of the ways to visualize data and communicate insights. This package offers a wide range of interactive charts including line charts, bar charts, pie charts, scatter plots, and much more. One of the best ways to work with Google Charts is through the R programming language. The googleVis package in R is a powerful tool that provides a simple interface for working with Google Charts. In this tutorial, we’ll take a detailed look at how to create and customize Google Chart Overlays using the googleVis package.

Installing the googleVis Package

The first step to using Google Charts in R is to install the googleVis package. This package is available on the CRAN repository and can be installed using the following command:

install.packages("googleVis")

Once the package is installed, it can be loaded into your R session using the following command:

library(googleVis)

Creating Google Chart Overlays in R

You can do many other things with the googleVis package in R to show Google Charts overlays, including:

Example 1:  Bar charts

You can create bar charts by using the gvisBarChart function.

Syntax: gvisBarChart(data, xvar = “”, yvar = “”, options = list(), chartid) 

Arguments:

  • data: a data.frame to be displayed as a bar chart.
  • xvar: Name of the character column which contains the category labels for the x-axes.
  • yvar: a vector of column names of the numerical variables to be plotted. Each column is displayed as a separate bar/column.
  • options: list of configuration options, see the Google Charts API documentation. This can be set via a named list.
  • chartid: a character. If missing (default) a random chart id will be generated based on chart type and tempfile.

Below is example of creating a Bar chart using  gvisBarChart():

R




library(googleVis)
  
# Create a bar chart of Sepal.Length, grouped by Species
barPlot <- gvisBarChart(iris, xvar = "Species", yvar = "Sepal.Length"
                        options = list(width = 400, height = 400))
  
# Plot the chart
plot(barPlot)


Output:

 

Example 2: Geochart

Geochart can be created using gvisGeoChart function. A Geochart is a visual representation of an area on a map.

Syntax: gvisGeoChart(data, locationvar = “”, colorvar = “”, sizevar = “”,  hovervar = “”, options = list(), chartid)

Argument:

  • data: a data frame with at least one column with the location name.
  • locationvar: column name of data with the geo-locations to be analyzed.
  • colorvar: column name of data with the optional numeric column used to assign a color to this marker.
  • sizevar: column name of data with the optional numeric column used to assign the marker size.
  • hovervar: column name of data with the additional string text displayed when the user hovers over this region.
  • options: list of configuration options.
  • chartid: character, a chart id will be generated based on chart type and tempfile if missing.

Below is an example of creating a gvisGeoChart of India using sample data:

R




# Load the googleVis library
library(googleVis)
  
# Create sample data with columns for location and profit
Exports <- data.frame(Country=c("India", "Pakistan", "Bangladesh"),
                      Profit=c(1000, 500, 200))
  
# Create the Geo Chart using the locationvar and colorvar options
Geo=gvisGeoChart(Exports, locationvar="Country"
                 colorvar="Profit",
                 options=list(projection="kavrayskiy-vii"))
  
# Plot the chart
plot(Geo)


Output: 

This created a geo-chart of India, with each country colored based on the profit value. The kavrayskiy-vii projection is used to display the map.

 

Example3: Customizing Points in a Scatter Chart

Scatter charts can be created using the gvisScatterChart function. A Scatter chart uses dot representation to visualize data. 

Syntax: gvisScatterChart(data, options = list(), chartid) 

Arguments:

  • data: a data.frame to be displayed as a scatter chart. Two or more columns are required, all must be numeric. The values in the first column are used for the X-axis. The values in following columns are used for the Y-axis. Each column is displayed with a separate color.
  • options: a list of configuration options. The parameters can be set via a named list. The parameters have to map those of the Google documentation.
  • chartid: a character string. If missing (default) a random chart id will be generated based on chart type and tempfile.

Below is an example of creating a scatter chart and customizing the appearance of the points by assigning a different shape to each group in the data.:

R




library(googleVis)
  
# Generate sample data
M <- matrix(nrow=6,ncol=6)
M[col(M)==row(M)] <- 1:6
data <- data.frame(X=1:6, M)
  
# Plot the scatter chart
scatter_chart <- gvisScatterChart(data, 
                                  options=list(
                                    title="Customizing Points in a Scatter Chart",
                                    legend="right",
                                    pointSize=30,
                                    series="{
                                      0: { pointShape: 'circle' },
                                      1: { pointShape: 'cross' },
                                      2: { pointShape: 'square' },
                                      3: { pointShape: 'diamond' },
                                      4: { pointShape: 'star' },
                                      5: { pointShape: 'triangle' }
                                      }",
                                    seriesType = "scatter"
                                  ))
  
plot(scatter_chart)


In the above example, we’ve used gvisScatterChart function to make a scatter chart from the data and used the options argument to customize the appearance of the chart. In particular, we specified pointShape for each group in the series argument which determines the shape of points on the chart. Along with we set the pointSize to 30 and legend position to “right”. Finally, we use the plot function to display the chart.

Output:

 

Example  4:  creating a candlestick chart 

The package provides several functions for creating financial charts, including candlestick charts. 

The gvisCandlestickChart function creates a new googleVis object of class “CandlestickChart” and takes a data frame as its input then creates a candlestick chart based on the data.

Syntax: gvisCandlestickChart( data, xvar = “”, low = “”, open = “”, close = “”, high = “”, options = list(), chartid)

Arguments:

  • data: A data.frame to be displayed as a candlestick chart. The data has to have at least 5 columns.
  • xvar: Character column which contains the category labels for the x-axes.
  • low: The name of the numeric column specifying the low/minimum value of this marker. This is the base of the candle’s center line.
  • open: It specifies the opening/initial value of this marker. It is one vertical border of the candle. If less than the close value, the candle will be filled; otherwise it will be hollow.
  • close: Specifying the closing/final value of this marker. It is the second vertical border of the candle. If less than the open value, the candle will be hollow; otherwise it will be filled.
  • high: Specifying the high/maximum value of this marker. This is the top of the candle’s center line.
  • options: List of configuration options, see the Google Charts API documentation. This can be set via a named list.
  • chartid: Character string. If missing, a random chart ID will be generated based on chart type and tempfile.

Below is an example of creating a candlestick chart using  gvisCandlestickChart():

R




library(googleVis)
library(quantmod)
# Load the AAPL dataset
getSymbols("AAPL", from='2023-01-01')
  
# Convert the data to a data frame
AAPL_df <- data.frame(Date = index(AAPL),
                      Open = as.numeric(Op(AAPL)),
                      High = as.numeric(Hi(AAPL)),
                      Low = as.numeric(Lo(AAPL)),
                      Close = as.numeric(Cl(AAPL)))
  
# Create the candlestick chart
chart <- gvisCandlestickChart(AAPL_df, options=list(title="AAPL Stock Prices"))
  
# Display the chart
plot(chart)


Output:

 

In the above example, we load the AAPL data set using getSymbols() that comes with the quantmod package. We then create a googleVis object of class “CandlestickChart” using the gvisCandlestickChart() function. We also customize the chart’s title using the options argument. Finally, we plot the chart using the plot() function.

Example 5: Timeline Chart

gvisTimeline function creates a Google Timeline chart that shows events over time. The timeline chart is used to display a sequence of events or an ordered set of values along a horizontal axis.

Syntax: gvisTimeline(data, rowlabel = “”, barlabel = “”, start = “”, end = “”, options = list(), chartid)

Argument:

  • data: A data frame that contains the data to be visualized.
  • rowlabel: A string that refers to the column name in data for the row labels to be used.
  • barlabel: A string that refers to the column name in data for the bar labels to be used.
  • start: Number, date, or datetime for the start dates.
  • end: Number, date, or datetime for the end dates.
  • options: A list of configuration options. The options are documented in detail by Google online. The parameters can be set via a named list. The parameters have to map those of the Google documentation.
  • chartid: Character. If missing (default) a random chart id will be generated based on chart type and tempfile.

Below is an example using the gvisTimeline function. In this example, we will create a timeline chart of events in different classrooms.

R




#Load the googleVis package
library(googleVis)
  
#Example data frame with four columns Datetime example
dat <- data.frame(Room=c("Classroom 1","Classroom 2","Classroom 3"),
Language=c("Statistics", "Mathematics", "Economics"),
start=as.POSIXct(c("2023-02-14 14:00", "2023-02-14 15:00",
"2023-02-14 14:30")),
end=as.POSIXct(c("2023-02-14 15:00", "2023-02-14 16:00",
"2023-02-14 15:30")))
  
#Create a timeline chart with the data
tl <- gvisTimeline(data=dat, rowlabel="Subject",
start="start", end="end")
  
#Display the chart
plot(tl)


Output:

In this example, we created a data frame with columns Room, Language, start, and end. We then passed this data frame to the gvisTimeline function, along with the rowlabel and start and end date columns. The resulting timeline chart shows the events in different classrooms, with the start and end times of each event.

 

Conclusion

Google Chart Overlays is another way to visualize data and communicate insights. This googleVis package in R provides a simple interface to work with Google Charts. In this tutorial, we’ve taken a detailed look at how to create and customize Google Chart Overlays using googleVis package. And also, how to export the charts to different file formats.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads