Daniel Valencia C.
Daniel Valencia C.

Reputation: 2279

Round points with similar values in a scatter plot using R and ggplot2

I have my data as XYZ triplet. For each XY pair exists a Z value. I'd like to plot the XY pairs in a scatter plot and round te values like the following example

enter image description here

In the MWE I'd like to round the Z values in 3 categories:

Any help please

  library(ggplot2)

x <- c(1,1.2,1.1,2,2.1,2.1,2.9,3,3.2)
y <- rep(seq(0,8,4),3)
z <- c(2,3,5,8,7,9,13,15,12)

DF <- data.frame(x,y,z)

ggplot(DF, aes(x,y,z)) +
  geom_point() +
  geom_text(label = z,
            hjust = 0,
            nudge_x = 0.05,
            nudge_y = 0.05)

enter image description here

Upvotes: 0

Views: 121

Answers (1)

Carles
Carles

Reputation: 2829

The library ggalt can help you doing the trick using the function geom_encircle() as follows:

library(ggplot2)
library("ggalt")

x <- c(1,1.2,1.1,2,2.1,2.1,2.9,3,3.2)
y <- rep(seq(0,8,4),3)
z <- c(2,3,5,8,7,9,13,15,12)

DF <- data.frame(x,y,z)

ggplot(DF, aes(x,y,z)) +
  geom_point() +
  geom_text(label = z,
            hjust = 0,
            nudge_x = 0.05,
            nudge_y = 0.05)+
geom_encircle(data=subset(DF, z<5), 
              color="red", 
              size=1, expand=0.04)+
geom_encircle(data=subset(DF, z<10), 
                color="blue", 
                size=1, 
                expand=0.06)+
geom_encircle(data=subset(DF, z<15), 
                color="black", 
                size=1, 
                expand=0.08)+ 
xlim(0,4)+ylim(-1,10)

enter image description here

For more information check https://rdrr.io/cran/ggalt/man/geom_encircle.html Cheers !

Upvotes: 1

Related Questions