Scatterplot Me

September 28, 2016
By

(This article was first published on R-SquareD, and kindly contributed to R-bloggers)

Plot the data within a png for fun –

Just for fun, I took my avatar image and plotted the png data into a scatterplot.

Me

It was relatively easy to do using the png package.

library(dplyr)
library(tidyr)
library(ggplot2)
library(ggthemes)
library(png)

# Read the png into a matrix. The png has three layers (see third dimension)
#  but I only care about one.
av = readPNG("../img/avatar-icon2.png")[,,1]
num_rows = NROW(av)
num_cols = NCOL(av)

# Add a column of row numbers
av = cbind(1:num_rows, av)

# Gather the matrix into three columns for easy plotting
df.av = av %>% as.data.frame() %>% gather("rows", "cols", 2:(num_cols+1))

# Clean up the data to make sure X and Y are integers
df.av$rows = as.integer(gsub("V", "", df.av$rows))
colnames(df.av) = c("Y", "X", "COL")
df.av$COL = round(df.av$COL, 3)

# For fun, calculate R^2 on the dark points of the data
lm_sum = df.av %>% filter(COL < .1) %$% lm(Y ~ X) %>% summary()
  
eq = substitute(~italic(r)^2~"="~r2, list(r2 = format(lm_sum$r.squared, digits = 3)))
eq_lab = as.character(as.expression(eq))

# Plot the data.frame
#  I reversed the y scale to get the image upright.
ggplot(df.av) +
  geom_point(aes(x=X, y=Y, color=COL)) +
  annotate("text", label=eq_lab, x = num_cols*.9, y = 10, color="white", parse=T, size=5.5)+
  scale_y_reverse() + 
  labs(title="", x="x", y="y", color="Col") +
  theme_classic()

plot of chunk unnamed-chunk-1

Wasn’t that fun!

To leave a comment for the author, please follow the link and comment on their blog: R-SquareD.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)