Last active
June 13, 2017 09:13
-
-
Save benmarwick/152bebd96eb359a9f379f4ec94bdb93a to your computer and use it in GitHub Desktop.
sparkbars in R Markdown
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
--- | |
output: html_document | |
--- | |
```{r, fig.show='hide', include=FALSE} | |
library(colformat) | |
x1 <- c("Using R Markdown and the colformats package we can put a sparkbar in | |
line with the text using inline R code, like this `` `r '\x60r spark_bar(x)\x60'` ``. | |
Here's a sparkbar showing a histogram of the number of characters | |
in each word in this text: `r spark_bar(x2)`. And here is a sparkbar | |
with the number of words per sentence: `r spark_bar(x3)`. | |
Pretty neat! In RStudio we do need to 'File -> Save with Encoding...' | |
and choose UTF-8 to ensure the bars appear correctly.") | |
# fn to convert values to a 0-1 range | |
range01 <- function(x, ...){(x - min(x, ...)) / (max(x, ...) - min(x, ...))} | |
x2 <- range01(hist(unname(sapply(unlist(strsplit(x1, " ")), nchar)))$counts) | |
x3 <- range01(sapply(strsplit(unlist(strsplit(x1, "\\. |\\? |\\! ")), " "), length)) | |
``` | |
Using R Markdown and the colformats package we can put a sparkbar in | |
line with the text using inline R code, like this `` `r '\x60r spark_bar(x)\x60'` ``. | |
Here's a sparkbar showing a histogram of the number of characters | |
in each word in this text: `r spark_bar(x2)`. And here is a sparkbar | |
with the number of words per sentence: `r spark_bar(x3)`. | |
Pretty neat! In RStudio we do need to 'File -> Save with Encoding...' | |
and choose UTF-8 to ensure the bars appear correctly. |
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
```{r} | |
library(htmlwidgets) | |
library(sparkline) | |
x = rnorm(10) | |
sparkline(x, spotColor = "") | |
``` | |
With the htmlwidgets & sparkline pkgs we can do authentic sparklines `r sparkline(x, spotColor = "")` in the middle of the text. | |
```{r, echo = TRUE} | |
library(colformats) | |
x <- seq(0, 1, length = 10) | |
spark_line(x) | |
``` | |
Where is the sparkline? `r spark_line(x)` Should be here. | |
Roses are <span style="color:red">red `r spark_line(x)`...</span> | |
Violets are <span style="color:blue">blue `r spark_line(x)`...</span> | |
<mark>Little sparkline `r spark_line(x)`</mark> | |
<span style="background-color: #FFFF00">Where are you? `r spark_line(x)`</span> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Love it!