Last active
May 10, 2022 16:00
-
-
Save NunoSempere/ffd985b2c39b461a55b1571cec8110ec to your computer and use it in GitHub Desktop.
Bivariate normals in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## install.packages(ggplot) | |
## install.packages(viridis) | |
## install.packages(ggthemes) | |
library(ggplot2) | |
library(viridis) | |
library(ggthemes) | |
## Build data | |
data <- list() | |
l <- 10000 | |
data$x <- rnorm(l, mean=1, sd=1) | |
data$y <- rnorm(l, mean=1, sd=1) | |
f <- function(x,y){ | |
return(sin(x*y)) | |
} | |
for(i in c(1:l)){ | |
data$color <- c(data$color,f(data$x[i], data$y[i])) | |
} | |
View(data) | |
data <- as.data.frame(data) | |
View(data) | |
## Simple plot | |
ggplot(data, aes(x=x,y=y)) + | |
geom_point(aes(colour=color)) | |
## Minimally more complicated plot | |
ggplot(data, aes(x=x,y=y)) + | |
geom_point(aes(colour=color))+ | |
labs(color = "Legend Title\n")+ | |
scale_color_viridis() | |
## Styled plot | |
title_text = "Blabitty blah blah" | |
subtitle_text = "By looking at this plot, I agree to give my immortal soul to Nuño Sempere" | |
label_x_axis = "label x axis" | |
label_y_axis = "label y axis" | |
label_color_legend = "label legend" | |
ggplot(data, aes(x=x,y=y)) + | |
geom_point(aes(colour=color))+ | |
theme_tufte() + | |
labs( | |
title=title_text, | |
subtitle=subtitle_text, | |
x=label_x_axis, | |
y=label_y_axis, | |
color=label_color_legend | |
) + | |
theme( | |
plot.title = element_text(hjust = 0.5), | |
plot.subtitle = element_text(hjust = 0.5), | |
legend.position="right", | |
legend.box="horizontal", | |
axis.text.x=element_text(angle=60, hjust=1), | |
) + | |
scale_color_viridis() | |
# Saving plots | |
## Saving the last plot | |
getwd() ## Working directory on which the file will be saved. Can be changed with setwd("/your/directory") | |
setwd("/home/loki/Documents/temp") ## or somewhere like that | |
height = 5 | |
width = height*1.05 ## floor(height*(1+sqrt(5))/2) | |
ggsave("alexplot.png", width=width, height=height) |
To get a rotation
angle_in_degrees = 60
angle_in_radians = (angle_in_degrees/360)*(2*pi)
for(i in c(1:l)){
y_old = data$y[i]
x_old = data$x[i]
x_new = x_old * cos(angle_in_radians) - y_old * sin(angle_in_radians)
y_new = x_old * sin(angle_in_radians) + y_old * cos(angle_in_radians)
data$x[i] = x_new
data$y[i] = y_new
data$color <- c(data$color,f(data$x[i], data$y[i]))
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result looks like: