Little useless-useful R functions – Making scatter plot from an image
[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Taking a jpg image and converting it to raster, getting pixelized data manipulation of the image and plot a scatter image.
Sound like another useless R function, that can produce a scatter plot in a shape of a logo with a smooth curve.
So the function is using the image manipulation part:
img <- magick::image_read("image/amazonLogo.jpg") img <- img %>% image_quantize(max=2, colorspace = 'gray', dither=TRUE) %>% image_scale(geometry = geometry_size_pixels(width=25, height=20, preserve_aspect=FALSE)) # Image manipulation mat <- t(1L - 1L * (img[[1]][1,,] > 180)) mat_df <-data.frame(mat)
Second part consists of data transformation to dataframe:
# Melt data dff <- data.frame(x = NULL, y = NULL) for (i in 1:nrow(mat_df)) { for (j in 1:ncol(mat_df)){ if (mat_df[i,j] == 1){ d <- data.frame(x=i, y=j) dff <<- rbind(dff, d) } } }
and last part is a simple ggplot scatter plot:
# draw scatter g <- ggplot(dff, aes(x = x, y = y)) + geom_point() + scale_x_reverse() + coord_flip() g + theme(panel.background = element_rect(fill = "white", colour = "grey")) #draw scatter with jitter g <- ggplot(dff, aes(x = x, y = y)) + geom_point() + geom_jitter() + scale_x_reverse() + coord_flip() g + theme(panel.background = element_rect(fill = "white", colour = "grey")) # draw scatter with smooth and CI g <- ggplot(dff, aes(x = x, y = y)) + geom_point() + scale_x_reverse() + coord_flip() + geom_smooth() g + theme(panel.background = element_rect(fill = "white", colour = "grey"))
As always, complete code is available at Github.
And some examples with famous logos:
And you can see the pattern
Happy R-ing! And stay healthy.
To leave a comment for the author, please follow the link and comment on their blog: R – TomazTsql.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.