How to name all circle in bubble chart in R?
In this article, we will see how to name all circles in a bubble chart in the R Programming language.
To add labels on each bubble in a bubble plot in the R Language, we use the geom_text() function of the ggplot2 package. The geom_text() function adds textual annotation overlap on top of the ggplot plot.
Syntax:
plot+ geom_text( aes( x, y, label, nudge_y, nudge_x )
Parameter:
- x and y: determines the position of the label.
- label: determines the vector that contains the labels for each bubble.
- nudge_y: determines the distance shift in the vertical direction for the label.
- nudge_x: determines the distance shift in the horizontal direction for the label.
In the below example, we will create a data frame and then plot a bubble plot with this data frame with no labels on each bubble.
Example: Basic plot
R
# create sample data frame x_value <- c (12,23,43,61,78,54,34,76,58) y_value <- c (12,54,34,76,54,23,43,61,78) radius <- c (1,5,13,8,12,3,2,16,7) label <- c ( "Label1" , "Label2" , "Label3" , "label4" , "label5" , "label6" , "label7" , "label8" , "label9" ) sample_data <- data.frame ( x_value, y_value, radius, label) # load library ggplot2 library ( ggplot2 ) # draw a basic bubble plot ggplot ( data = sample_data, aes ( x=x_value, y=y_value, size=radius, color=label ) )+ geom_point (alpha=0.4)+ |
Output:
Now to add text to the plot we use, geom_text().
Example: Adding text to the plot
R
# create sample data frame x_value <- c (12,23,43,61,78,54,34,76,58) y_value <- c (12,54,34,76,54,23,43,61,78) radius <- c (1,5,13,8,12,3,2,16,7) label <- c ( "Label1" , "Label2" , "Label3" , "label4" , "label5" , "label6" , "label7" , "label8" , "label9" ) sample_data <- data.frame ( x_value, y_value, radius, label) # load library ggplot2 library ( ggplot2 ) # draw a basic bubble plot ggplot ( data = sample_data, aes ( x=x_value, y=y_value, size=radius, color=label ) )+ geom_point (alpha=0.4)+ geom_text ( aes (label=label)) |
Output:
To adjust the position of the label of the bubble in the bubble plot, we use nudge_x and nudge_y.
Example: Adjusting labels
R
# create sample data frame x_value <- c (12,23,43,61,78,54,34,76,58) y_value <- c (12,54,34,76,54,23,43,61,78) radius <- c (1,5,13,8,12,3,2,16,7) label <- c ( "Label1" , "Label2" , "Label3" , "label4" , "label5" , "label6" , "label7" , "label8" , "label9" ) sample_data <- data.frame ( x_value, y_value, radius, label) # load library ggplot2 library ( ggplot2 ) # draw a basic bubble plot ggplot ( data = sample_data, aes ( x=x_value, y=y_value, size=radius, color=label ) )+ geom_point (alpha=0.4)+ scale_size (range = c (1,13) )+ geom_text ( aes (label=label), nudge_y= -3, nudge_x= -2)+ theme (legend.position = "none" ) |
Output: