Little useless-useful R functions – Making scatter plot from an image
This article is originally published at https://tomaztsql.wordpress.com
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.
Thanks for visiting r-craft.org
This article is originally published at https://tomaztsql.wordpress.com
Please visit source website for post related comments.