Last active
April 23, 2020 01:03
-
-
Save timelyportfolio/fb5819e78a904d7b61f1186ccb7a0e4b to your computer and use it in GitHub Desktop.
rotate and fit scatterD3
This file contains hidden or 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
library(htmltools) | |
library(scatterD3) | |
sd3 <- scatterD3(x = mtcars$wt, y = mtcars$mpg, data=NULL, lab = rownames(mtcars), | |
col_var = mtcars$cyl, symbol_var = mtcars$am, | |
xlab = "Weight", ylab = "Mpg", col_lab = "Cylinders", | |
symbol_lab = "Manual transmission", html_id = NULL, height = 300, width = 500) | |
browsable( | |
tags$div( | |
htmlwidgets::onRender( | |
sd3, | |
" | |
function(el, x) { | |
debugger | |
// hard coded for now assuming we want to rotate 45 degrees | |
var degrees = 45; | |
// https://stackoverflow.com/questions/622140/calculate-bounding-box-coordinates-from-a-rotated-rectangle | |
function fitRect( rw,rh,degrees ){ | |
var radians = degrees * Math.PI / 180; | |
var x1 = -rw/2, | |
x2 = rw/2, | |
x3 = rw/2, | |
x4 = -rw/2, | |
y1 = rh/2, | |
y2 = rh/2, | |
y3 = -rh/2, | |
y4 = -rh/2; | |
var x11 = x1 * Math.cos(radians) + y1 * Math.sin(radians), | |
y11 = -x1 * Math.sin(radians) + y1 * Math.cos(radians), | |
x21 = x2 * Math.cos(radians) + y2 * Math.sin(radians), | |
y21 = -x2 * Math.sin(radians) + y2 * Math.cos(radians), | |
x31 = x3 * Math.cos(radians) + y3 * Math.sin(radians), | |
y31 = -x3 * Math.sin(radians) + y3 * Math.cos(radians), | |
x41 = x4 * Math.cos(radians) + y4 * Math.sin(radians), | |
y41 = -x4 * Math.sin(radians) + y4 * Math.cos(radians); | |
var x_min = Math.min(x11,x21,x31,x41), | |
x_max = Math.max(x11,x21,x31,x41); | |
var y_min = Math.min(y11,y21,y31,y41); | |
y_max = Math.max(y11,y21,y31,y41); | |
return [x_max-x_min,y_max-y_min]; | |
} | |
// partial solution assuming width < height | |
var width = el.offsetWidth; | |
var height = el.offsetHeight; | |
var sizes = fitRect(width, height, degrees); | |
var newWidth = sizes[0]; | |
var newHeight = sizes[1]; | |
d3v4.select(el) | |
.style('width', newWidth + 'px') | |
.style('height', newHeight + 'px'); | |
d3v4.select(el).select('svg') | |
.attr('transform','rotate(' + degrees + ')') | |
.style('margin-top', (newHeight - height) / 2) | |
.style('margin-left', (newWidth - width) / 2) | |
} | |
" | |
) | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment