Scatterplot Me

[This article was first published on R-SquareD, 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.

Plot the data within a png for fun –

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


It was relatively easy to do using the png package.


# 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 %>% %>% 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") +

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. 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.

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)