Bubble Chart in R, A bubble chart is majorly used to show the relationships between numeric variables and it can visualize two to four dimensions.
The first two dimensions for coordinates, the third dimension is for color and the fourth as size.
Bubble chart is an enhancement of the normal scatter plot instead of traditional dots or points in the scatter plot are replaced by circles or bubbles.
In this article will describe how to create bubble chart based on ggplot2 and plotly.
Bubble Chart in R
First, load ggplot2 package in R
In ggplot2 allows to render almost all type of charts and graphs. In this article approach is like load the library, create a data frame and display plot.
Load the data from mtcars
data("mtcars") df <- mtcars
Let’s convert cyl as a grouping variable
df$cyl <- as.factor(df$cyl)
Let’s see the data frame
head(df[, c("wt", "disp", "cyl", "qsec")]) wt disp cyl qsec Mazda RX4 2.620 160 6 16.46 Mazda RX4 Wag 2.875 160 6 17.02 Datsun 710 2.320 108 4 18.61 Hornet 4 Drive 3.215 258 6 19.44 Hornet Sportabout 3.440 360 8 17.02 Valiant 3.460 225 6 20.22
Points size is controlled by a continuous variable, in this case qsec. argument alpha is used to control color transparency and should lies between 0 and 1.
ggplot(df, aes(x = wt, y = disp)) + geom_point(aes(color = cyl, size = qsec), alpha = 0.5) + scale_color_manual(values = c("#AA4371", "#E7B800", "#FC4E07")) + scale_size(range = c(1, 13)) + # Adjust the range of points size theme_set(theme_bw() +theme(legend.position = "bottom"))
library(plotly) bubbleplot <- plot_ly(df, x = ~wt, y = ~disp, text = ~cyl, size = ~qsec, color = ~cyl, sizes = c(10, 50), marker = list(opacity = 0.7, sizemode = "diameter")) bubbleplot <- bubbleplot%>%layout bubbleplot
Enjoyed this article? Don’t forget to show your love, Please Subscribe the Newsletter and COMMENT below!