GithubHelp home page GithubHelp logo

timelyportfolio / sunburstr Goto Github PK

View Code? Open in Web Editor NEW
207.0 21.0 124.0 1.32 MB

R htmlwidget for interactive sunburst plots

Home Page: http://timelyportfolio.github.io/sunburstR/articles/sunburst-2-0-0.html

License: Other

R 8.79% CSS 0.17% JavaScript 91.04%
rstats htmlwidgets d3 visualization package interactive javascript r chart

sunburstr's Introduction

R-CMD-check CRAN status

Help Me/Pay Me to Use, Improve, and Extend

sunburstR has already seen extensive use in many projects across multiple domains. If you have any interest in collaborating with me on this project or applying sunburstR, please let me know (see Time Isn't Money).

sunburstR

Easily make these interactive d3.js sequence sunburst charts in R originally modeled on this example from Kerry Rodden. In addition, sunburstr provides another beautiful and functional version using d2b from Kevin Warne.

Examples

See the examples.

Improve/Iterate

These are still far from feature-complete. I would love your input, feedback, and comments.

Code of Conduct

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

sunburstr's People

Contributors

abresler avatar cjyetman avatar jonmcalder avatar timelyportfolio avatar vanamsterdam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sunburstr's Issues

reoder slides and thickness

Hi @timelyportfolio ,

First of all, many thanks for sharing this very nice sunburst function.
I have some questions/suggestions:

  1. It would be possible to add an example about how to use the Sortfunction, it is not clear for me how to proceed. Here a simple table:
    close_reference-fungi_assigned 666764
    denovo-denovo_unassigned 979579
    denovo-denovo_unidentified 568157

sunburst(otu_picking, count=T, percent=T, legend=list(w=120,h=18,s=2,t=1)).

Generate a sunburst starting with the unassigned, but I would like that the close_reference start first clockwise.
2) It would be possible to manage the thickness of each level by an R function?
3) When not interaction is possible (during a ppt presentation) it would be possible to add the description, similar to the uploaded image?

Many thanks, Eric
Phd ecology student

q68sb

passing data selected from on click

I would like to pass data selected from on click to server side for downloading it in shiny. So far, I have tried to use your great examples, to no avail. I would appreciate some help.

shiny integration

Thanks for this great package @timelyportfolio - Just wondering if you've attempted shiny integration here yet. You've included sunburstOutput() and renderSunburst(), and these work great right off the bat. But I've noticed a strange behavior -

If we try to produce a new result from renderSunburst() in response to any user input, the resulting plot seems to append the relevant data instead of replacing it.

Here's a simple example to demo.

https://github.com/keeganhines/sunburstRshiny

This is most noticeable as the label grows and grows as you interact with the slider. I'm kinda stumped, I can't imagine what aspect of htmlwidgets is appending the data. Do you have any guess?

Have legend on as a default?

Is it possible to not have to click to see the legend?

edit: in light of "time != money" which I agree with completly given my year old daughter ;) I'm happy to help with coding it if you point me in the right direction and think it possible. I've used sunburstR for a while for web analytics multi-touch analysis and it rocks.

refactor JS code to separate modules

After converting to d3v4, I would like to modularize the JS code to resemble Let's Make a D3 Plugin. As an example of this, I have done d3horizonR. d3horizonR is not perfect, but demonstrates how the JS lives in its own separate directory ignored by the R pkg. The JS gets processed, built, and compiled and then moves to the inst/htmlwidgets folder for use by the R package. The advantage is we can stick to a "modern" typical JS build and test workflow.

See leaflet as another example.

Potential Modules

A quick round of code analysis reveals some clear module opportunities.

  • HTMLWidgets module, but this should be separate from the main JavaScript build
  • Vis layout module
  • Breadcrumb module
  • Legend module
  • Hierarchy builder and helper module

Edit breadcrumb text

Hi Kent and all,

Is it possible to modify the text of each breadcrumb element that is displayed at the very top of the plot? An example could be suppose that I am looking at a sequence of things, but I'd also like to know the duration of every element in the sequence. That is, if I am looking at the sequence A -> B -> C, I'd like to know the mean duration of A (when A is the first element in the sequence), the mean duration of B (when B is the second element in the sequence) and the mean duration of C (when C is the third element in the sequence). So basically, I'd like to know the mean duration (or any arbitrary statistic) for every element in every sequence. My thought was that if I could edit the breadcrumb text, I could somehow paste that information in there after computing it myself. But, I haven't an idea of how to access that information, as the "explanation" parameter is for the center of the sunburst plot only.

What do you think, and do you have any suggestions?

Thanks for your time again!

Explanation argument

I can't seem to use a user defined JS function in the explanation that returns d.name and d.percent, but the d object does not have a percent value. For example:

sunburst(sequence_data, explanation = "function(d) {return [d.name, d.value]}")

The code above works, but this one below not:

> (x <- sum(sequence_data$V2))
[1] 41768062
> sunburst(sequence_data, explanation = "function(d) {return d.value / x}")

Is there another way to show d.name and percent in the output

Is there a limit to the depth?

Really nice package! I've been applying it to structural path analysis in environmental life cycle assessment. I have been running into an error though. When I select a depth of greater than 12 the sunburst that's rendered leaves a gap. Are you aware of any limitation in terms of # of layers or any other constraint that might be causing the rendered sunburst to leave a missing piece of the pie?

BREAK API - change data argument

It has bothered me for quite a while that sunburst() takes two arguments to pass data. I would much prefer the approach in d3treeR that takes one data argument and attempts to resolve based on class. I have not changed for fear of breaking the API, but since we are taking major step in version, I think I will make the adjustment. Any feedback??

Unnatural splitting of sequence step

There seems to be a sequence problem with the latest version of the package.

The issue is that the last sequence in a path is being split.

Here's a sample of what the issue looks like:
output_znran5

Does anyone have the previous version?

Font size of legend

@timelyportfolio I am trying to figure out how to change the font size of the legend, would you please give an example of changing the font size of legend? Also, do you have any idea of changing the size of sunburst chart itself(not the legend)?

Thank you for your great job!

Selina

standalone d3v4 build

Build the JS dependency as a standalone file, so we do not face d3v3 vs. d3v4 type issues again. See d3horizonR and the forked d3sankey as examples. This should be fairly straightforward.

Legend SurnBurstR

Hi,
I want to know if it possible to reduce the legend (manipulate the legend area) in Sunburst graph ?

Tks a lot.

Mimeides

Add Shiny to d2b

Add Shiny to d2b. Most likely will push this to a future release > 2.0.0.

Separate Dark/Light Text Colours in Legend

Similar to this implementation in statebins (explained in the second code chunk in Downsizing) is it possible to supply different text colours to the legend to maximise legibility? For example, in the below example, light colours would keep the black text, but the darker shades would get white:

sunburst

does this library function on d3 vs 3.5.15 vs 3.5.17 ?

My company has an internal third_party library for R packages, and wants me to use existing d3.min.js in third_party that is only versioned to 3.5.15. Due to d3 v3 deprecation, they will not want me to update to 3.5.17 for offline use in d3r package that sunburstR relies on.

Is there a critical issue if I were to use 3.5.15 instead of 3.5.17?

conditionalPanel causes breadcrumbs in sunburstR not to display in shiny

I would like to find a way to get breadcrumbs to display in the non default panel. Is it possible.

install.packages("sunburstR")
library(shiny)
library(sunburstR)
ui <- fluidPage(

  fluidRow(
    column(4, id = "tiers",
           selectInput('tiers', 'Select Option', choices = c('AA', 'BB'), selectize=TRUE))

  ),

  fluidRow(
    conditionalPanel(
      condition = "input.tiers == 'AA'",
      column(4,
             div(h4("Hierachy View A"),
                 sunburstOutput("sunburst", height = 280), style = "width:100%; margin: auto"))
    ),

    conditionalPanel(
      condition = "input.tiers != 'AA'",
      column(4,
             div(h4("Hierachy View B"),
                 sunburstOutput("sunburst1", height = 280), style = "width:115%; margin: auto"))
    )

  )


)


server <- function(input,output,session){
  reports <- data.frame(sequence = c("SVP-VP-Dir-end","SVP-VP-EDir-end","SVP-VP-Dir-end","SVP-VP-Dir-end","SVP-No VP-Dir-end","SVP-No VP-Dir-end","SVP-No VP-Dir-end"),
                        freq = as.numeric(c("167","60","51","32","5","1","1")))

  output$sunburst <- renderSunburst({ 
    invalidateLater(1000, session)
    sunburst(reports, explanation = "function(d){return d.value}") 
  })

  output$sunburst1 <- renderSunburst({ 
    invalidateLater(1000, session)
    sunburst(reports, explanation = "function(d){return d.value}") 
  })
}

shinyApp(ui = ui, server = server)

Is it possible to size wedges by area instead of length?

Sorry to ask this question as an "issue". I couldnt find a mailing list so posting this here.

Is it possible to have sunburst represent the size by area instead of by length.

I am aware of the pluses of "length" visually rather than area perception..but I was wondering if there is a way for sunburst to switch to a mode where it sizes the wedges by area.

Shiny implementation: Plot is not rendering correctly

Thanks for the widget, really like it.

I am trying to use it in a shiny App. However, the plot doesn't seem to render correctly.
I tried to use the example in the package. It is showing fine in the RStudio Viewer. However, when I run the shinyApp, the plot is not showing. It shows the legend, but the legend keeps flashing and changing.

Any ideas or suggestion that I can get it working would be greatly appreciated.

Thanks a lot and keep up with the good work. :)

HTML file exported with "Save as Web Page..." from RStudio Viewer is broken

I've generated it in RStudio using code "Sunburst 1" from https://github.com/timelyportfolio/sunburstR/blob/master/inst/examples/example_flexdashboard.Rmd .

Exported HTML file for some reason contains an escaped fragment:

<pre><code>&lt;div&gt;
  &lt;div class=&quot;sunburst-main&quot;&gt;
    &lt;div class=&quot;sunburst-sequence&quot;&gt;&lt;/div&gt;
    &lt;div class=&quot;sunburst-chart&quot;&gt;
      &lt;div class=&quot;sunburst-explanation&quot; style=&quot;visibility:hidden;&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div class=&quot;sunburst-sidebar&quot;&gt;
    &lt;input type=&quot;checkbox&quot; class=&quot;sunburst-togglelegend&quot;&gt;Legend&lt;/input&gt;
    &lt;div class=&quot;sunburst-legend&quot; style=&quot;visibility:hidden;&quot;&gt;&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</code></pre>

Zoomable sunburst and underlaying circle

Hi there,
I've been using this package for quite a bit of time now, and along with shiny and some input to manually choose which hierarchy you want to see, you can quickly explore your data and that's great.
However I still miss the zoomable feature which could allow to dig deeper in the chosen hierarchy, allowing for deeper hierarchy.

How hard would it be to add the arcTween function, as seen in action here for instance :
https://bl.ocks.org/WangQiru/effe919b93164bca9f59b73d37577ef1

I also like a lot the underlaying grey circle as seen here :
http://www.brain-map.org/api/examples/examples/sunburst/

I've managed to get it done somewhere in a modified version of sunburst.js but I could not find it. I've added things like :
var arcHighlight = d3.svg.arc() .startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); }) .endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); }) .innerRadius(function(d) { return !isParent(d) ? r - outerRadius : Math.max(0, y(d.y + d.dy)); }) .outerRadius(function(d) { return r; });
and some animations as well to make it smoother with path.transition() .duration(750) in the mouseover function.

I've never been able to make the arcTween function do what it's supposed to do, but I'm not a js guru :)

Any help would be appreciated on both topics.

Keep up the good work !

Incorrect numbers due to rounding

Hi,

I have found a problem in the way the (displayed) numbers are computed. It seems the problem comes from the rounding. Example, if my actual numbers on the edge of the chart are 0.775%, they get rounded to 0.78%. Let's assume I have 4 such slices for a correct total of 3%. The circle a level above will have a slice displaying not 3% but 3.12%, that is, 4*0.78%(rounded). In effect, the use of rounded number compounds imprecisions as one goes further up the chart.
snap4
snap7
snap8

Browsable, renderUI or Sunburst?

Based on this http://timelyportfolio.github.io/sunburstR/example_baseball.html example (use sunburst event), I want to wrapped it into an interactive shiny app (the click on within an interactive shiny app). What I did previously is put the (browsable function/tagList) into the renderUI function,

`output$sunburst = renderUI({tagList(
sb,
tags$div(id="games", style="margin-top:100px"),
tags$script(HTML(
sprintf(
'
var action = %s;

function mouseovered(d){
var games = action.filter(function(evt){
return evt.event === d.join("-");
});

var div = document.getElementById("games");
div.innerHTML = games.map(function(game){
return [
"<a href='http://gd2.mlb.com/components/game/mlb/year_2016/month_08/day_25/",
game.gameday_link,
"'>",
game.gameday_link,
"
"
].join("");
}).join("\n");
}
',
jsonlite::toJSON(action, auto_unbox=TRUE, dataframe="row")
)
))
)})`

It works fine. But after I updated the sunburst package from 0.6.2 to 0.6.3, the generated sunburst chart is not shown up in the app. So I am wondering which parts has change resulting in the in-compatible of browsable/sunburst with renderUI

My current shiny version is shiny_0.14, R and R studio version is 3.3.2 and 0.99.902

Many thanks

CRAN-bound

sunburstR will be CRAN-bound by the end of the week 2016-08-20. I would love suggestions, improvements, examples to make it as good as possible before it is an official R package.

How can I completely remove the legend?

I'm looking for a way to remove the initialization of the legend. I've commented out all code that I thought was to do with the legend (in sunburst.js) and now the Legend toggle doesn't work. However, I don't want to see the Legend label and toggle. Any idea what I'm missing? Thanks a lot.

Please make this package available on CRAN.

Github is blocked at my workstation (Yes, I know it's ridiculous) so I cannot download your package using devtools. I know I can download it as a zip file and send it to my work email but it would be easier for me if I could just downloads from CRAN.

Controlling colours across plots

The package is great, thanks.

However, I have been struggling to understand how the colors and legendOrder arguments to sunburst work.

I am trying to create separate plots for different dates for example, but I want to keep the colours for individual categories the same across plots.

Below is some reproducible code to show what I have tried, with no success. I have also attempted to specify legendOrder along with manual colour specification, but the colours diverged (i.e. category a in the first plot had a different colour from category a in the second plot.

Any pointers to misunderstandings on my part, as well as any insight into a solution are very welcome.

Thanks

Kevin

library(sunburstR)
library(RColorBrewer)
library(dplyr)
# reproducable problem
df <- data.frame(date = rep(seq(Sys.Date(), length = 2, by = '1 day'), each = 10))
df$relationships <- unlist(
  lapply(1:2, function(i){
    unlist(
      lapply(1:10, function(ii){
        paste0(sample(letters[1:10], sample(3:5, 1), replace = FALSE), collapse = '-')
      })
    )
  })
)
df <- split(df, df$date)
df <- do.call(
  rbind,
  lapply(df, function(x){
    n = round(runif(nrow(x), min = 1, max = 100))
    x$n <- (n/sum(n))*100
    x
  })
)
rownames(df) <- NULL

legend_items <- unique(unlist(strsplit(df$relationships, '-')))
cols <- sample(colorRampPalette(brewer.pal(12, 'Set3'))(length(legend_items)))

# plot each date
plt_fun <- function(flt_date){
  # filter for dt
  plt_df <- df %>%
    filter(date == flt_date) %>%
    select(-date)

  plt_legend <- unique(unlist(strsplit(plt_df$relationships, split = '-')))
  # get the colours for legends items in plt_df
  plt_cols <- cols[match(plt_legend, legend_items)]
  sunburst(plt_df, colors = plt_cols)
}

plt_fun(unique(df$date)[1])
plt_fun(unique(df$date)[2])

Big variable names overlapping in output

This is how big are the variable names I'm talking about:

> head(df2)
                                       sequencia volume
1 Critica Pedido-Alçada: CAF-Cód.Crítica: 000001     15
2 Critica Pedido-Alçada: CAF-Cód.Crítica: 000002     10
3 Critica Pedido-Alçada: CAF-Cód.Crítica: 000013      4
4 Critica Pedido-Alçada: CAF-Cód.Crítica: 000051      1
5 Critica Pedido-Alçada: CAF-Cód.Crítica: 000154     10
6 Critica Pedido-Alçada: ETP-Cód.Crítica: 000152     34
> tail(df2)
                                                                 sequencia volume
39 Devolução-Resp: 000008 - TRANSPORTADORA -Motivo: 000083 - PROPRIETARIO       7
40 Devolução-Resp: 000008 - TRANSPORTADORA -Motivo: 000087 - TEMPO INSUFIC     24
41 Devolução-Resp: 000008 - TRANSPORTADORA -Motivo: 000089 - PDV FECHADO A      4
42                                                            Falta Real--    120
43                                         Pedido Orfão-Orfão Faturamento-      4
44                                         Pedido Orfão-Orfão Roterização-      6

What happens is when I output this data.frame in sunburstR, the variable names overlap in the output and I can't see the percent result of that piece of the sequence, as I try to show in the image below:

http://imgur.com/LEeFZU8

Is there a workaround for this or should I use shorter strings for the variables?

on.click event + colour question

Is it possible to have on.click events for the Sunburst sections, like can be coded in D3?
.on("click", function (d) {

});
I want to code a URL into the action based on values in the data, so I can drill down into the population of values represented in that section of the Sunburst.

A second question: How is colour assigned to the categories in the Sunburst? Is it based on frequency count of the categories? Can it be set manually, to assign colours directly to categories, regardless of their order?

Thanks again for this excellent sunburst.

Tim

plot not generating

I'm having trouble generating a plot with my own data and was wondering if there were any character or path/character length limitations that should be kept in mind.

handle pre-summed trees

promoting #60 (comment) started by @jstrin


@timelyportfolio I was playing with the d2b sunburst example you posted and noticed that the way the data is aggregated and formatted using the treemap::treemap function, it is causing some of the data to be aggregated resulting in inaccurate counts. For example, if you take a look at the "C" nodes in the example, the raw data (from the JSON) is:

Var Value
C 3.0517
C.1 3.0517
C.1.a. 0.8251
C.1.b. 1.6427
C.1.c 0.5839

C.1.a + C.1.b + C.1.c = C.1 = C

However, the javascript appears to aggregate the data moving down the hierarchy for the sunburst. When you look at the plotted value for C it is displaying as 9; C.1 is displaying as 6. In other words -
C.1.a + C.1.b + C.1.c + C.1 = C.1'
C.1.a + C.1.b + C.1.c + C.1 + C = C'

Where C.1' and C' are the displayed values in the final visualization.

I found that aggregating my data then passing it to the treemap::treepallette function was a quick fix to this:

hier_json <- df %>%
    group_by( index1, index2, index3, index4) %>%
    summarise( size = n( ) ) %>%
    treepalette( ) %>%
    select( index1, index2, index3, index4, size, color = HCL.color) %>%
    d3_nest( value_cols = c( "size", "color"))

If you are looking for assistance putting together htmlwidgets for the d2b sunburst (and/or the d2b bubble chart) I'm happy to do what I can.

Rounding in count parameter

Hi Kent,

To begin, thank you for this incredibly helpful and easy to use package. I noticed that it seems like there is rounding that occurs in the count/explanation portion of the figure. This rounding seems to be scaled logarithmically. Might you know of any work around, like perhaps a custom "explanation" parameter like explanation = "function(d){return d.data.name}", to remove this rounding convention? I understand that the sunburst plot is meant to give ballpark market share/sequence numbers and is not meant for any "rigorous" analyses where that level of precision should matter, but it would still be nice to see more exact counts. For example, I'd like to see a count of 105 instead of 110.

Thank you so much for your time!

Exclusive breadcrumb

First of all, thank you for the great widget, it's my favorite HTML widget in R.

I've been trying to generate flexdashboard that contains two sunbursts.
a weird behavior occurs when one of the sunburst didn't show the sequence breadcrumb, after investigating, it seems like the breadcrumb is Exclusive for one sunburst (first sunburst to hover over).

Add vignettes

add vignettes possibly using tint or some other Rmd template demonstrating not only how to include sunburstR but also other htmlwidgets

an example Rmd using the example from tint


title: "Tint Is Not Tufte"
subtitle: "An implementation in R Markdown"
author: "JJ Allaire, Yihui Xie, Dirk Eddelbuettel"
date: "r Sys.Date()"
output: tint::tintHtml
bibliography: skeleton.bib
link-citations: yes

vignette: >
%\VignetteIndexEntry{tint HTML Example}
%\VignetteKeywords{tint,vignette}
%\VignettePackage{tint}
%\VignetteEngine{knitr::rmarkdown}

library(ggplot2)
library(tint)
# invalidate cache when the package version changes
knitr::opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tint'), cache=FALSE)
options(htmltools.dir.version = FALSE)

Before We Get Started...

library(sunburstR)
library(htmltools)
rhd <- treemap::random.hierarchical.data()
tags$div(
  class = "marginnote shownote",
  style="width: 30%; margin-right:10%;",
  sunburst(
    d3r::d3_nest(rhd, value_cols = "x"),
    valueField = "x",
    width = "100%",
    height = 400
  )
)

tint is straightforward mix of the (html and pdf
parts of the) excellent tufte package by JJ and Yihui,
mixed with the Roboto Condensed font
use and color scheme proposed by envisioned css
plus minor style changes such as removal of italics---but otherwise true to the
wonderful tufte package for R---all baked together
into a small package providing another template.

We support italic aka em and strong annotations for text, as well as code snippets.

The package name is a standard package naming recursion: tint is not tufte.

The remainder of the tufte skeleton document follows
as is, with only marginal changes to refer to this package for code, and to minimize
dependencies^[The default smoother used in some of the plots would require the
mgcv package.].

Introduction

The Tufte handout style is a style that Edward Tufte uses in his books and handouts. Tufte's style is known for its extensive use of sidenotes, tight integration of graphics with text, and well-set typography. This style has been implemented in LaTeX and HTML/CSS^[See Github repositories tufte-latex and tufte-css], respectively. We have ported both implementations into the tufte package. If you want LaTeX/PDF output, you may use the tufte_handout format for handouts, and tufte_book for books. For HTML output, use tufte_html. These formats can be either specified in the YAML metadata at the beginning of an R Markdown document (see an example below), or passed to the rmarkdown::render() function. See @R-rmarkdown for more information about rmarkdown.

---
title: "An Example Using the Tufte Style"
author: "John Smith"
output:
  tufte::tufte_handout: default
  tufte::tufte_html: default
---

There are two goals of this package:

  1. To produce both PDF and HTML output with similar styles from the same R Markdown document;
  2. To provide simple syntax to write elements of the Tufte style such as side notes and margin figures, e.g. when you want a margin figure, all you need to do is the chunk option fig.margin = TRUE, and we will take care of the deails for you, so you never need to think about \begin{marginfigure} \end{marginfigure} or <span class="marginfigure"> </span>; the LaTeX and HTML code under the hood may be complicated, but you never need to learn or write such code.

If you have any feature requests or find bugs in tufte, please do not hesitate to file them to https://github.com/rstudio/tufte/issues. For general questions, you may ask them on StackOverflow: http://stackoverflow.com/tags/rmarkdown.

Headings

This style provides first and second-level headings (that is, # and ##), demonstrated in the next section. You may get unexpected output if you try to use ### and smaller headings.

r newthought('In his later books')^[Beautiful Evidence], Tufte starts each section with a bit of vertical space, a non-indented paragraph, and sets the first few words of the sentence in small caps. To accomplish this using this style, call the newthought() function in tufte in an inline R expression `r ` as demonstrated at the beginning of this paragraph.^[Note you should not assume tufte has been attached to your R session. You should either library(tufte) in your R Markdown document before you call newthought(), or use tint::newthought().]

Figures

Margin Figures

Images and graphics play an integral role in Tufte's work. To place figures in the margin you can use the knitr chunk option fig.margin = TRUE. For example:

library(ggplot2)
mtcars2 <- mtcars
mtcars2$am <- factor(
  mtcars$am, labels = c('automatic', 'manual')
)
ggplot(mtcars2, aes(hp, mpg, color = am)) +
  geom_point() + geom_smooth(method="loess", span=0.8) +
  theme(legend.position = 'bottom')

Note the use of the fig.cap chunk option to provide a figure caption. You can adjust the proportions of figures using the fig.width and fig.height chunk options. These are specified in inches, and will be automatically scaled down to fit within the handout margin.

Arbitrary Margin Content

In fact, you can include anything in the margin using the knitr engine named marginfigure. Unlike R code chunks ```{r}, you write a chunk starting with ```{marginfigure} instead, then put the content in the chunk. See an example on the right about the first fundamental theorem of calculus.

We know from _the first fundamental theorem of calculus_ that for $x$ in $[a, b]$:
$$\frac{d}{dx}\left( \int_{a}^{x} f(u)\,du\right)=f(x).$$

For the sake of portability between LaTeX and HTML, you should keep the margin content as simple as possible (syntax-wise) in the marginefigure blocks. You may use simple Markdown syntax like **bold** and _italic_ text, but please refrain from using footnotes, citations, or block-level elements (e.g. blockquotes and lists) there.

Full Width Figures

You can arrange for figures to span across the entire page by using the chunk option fig.fullwidth = TRUE.

ggplot(diamonds, aes(carat, price)) + geom_point(size=0.5, alpha=0.1) + facet_grid(~ cut)

Other chunk options related to figures can still be used, such as fig.width, fig.cap, out.width, and so on. For full width figures, usually fig.width is large and fig.height is small. In the above example, the plot size is $10 \times 2$.

Main Column Figures

Besides margin and full width figures, you can of course also include figures constrained to the main column. This is the default type of figures in the LaTeX/HTML output.

ggplot(diamonds, aes(cut, price)) + geom_boxplot()

Sidenotes

One of the most prominent and distinctive features of this style is the extensive use of sidenotes. There is a wide margin to provide ample room for sidenotes and small figures. Any use of a footnote will automatically be converted to a sidenote. ^[This is a sidenote that was entered using a footnote.]

If you'd like to place ancillary information in the margin without the sidenote mark (the superscript number), you can use the margin_note() function from tufte in an inline R expression. r margin_note("This is a margin note. Notice that there is no number preceding the note.") This function does not process the text with Pandoc, so Markdown syntax will not work here. If you need to write anything in Markdown syntax, please use the marginfigure block described previously.

References

References can be displayed as margin notes for HTML output. For example, we can cite R here [@R-Base]. To enable this feature, you must set link-citations: yes in the YAML metadata, and the version of pandoc-citeproc should be at least 0.7.2. You can always install your own version of Pandoc from http://pandoc.org/installing.html if the version is not sufficient. To check the version of pandoc-citeproc in your system, you may run this in R:

system2('pandoc-citeproc', '--version')

If your version of pandoc-citeproc is too low, or you did not set link-citations: yes in YAML, references in the HTML output will be placed at the end of the output document.

Tables

You can use the kable() function from the knitr package to format tables that integrate well with the rest of the Tufte handout style. The table captions are placed in the margin like figures in the HTML output.

knitr::kable(
  mtcars[1:6, 1:6], caption = 'A subset of mtcars.'
)

Block Quotes

We know from the Markdown syntax that paragraphs that start with > are converted to block quotes. If you want to add a right-aligned footer for the quote, you may use the function quote_footer() from tufte in an inline R expression. Here is an example:

"If it weren't for my lawyer, I'd still be in prison. It went a lot faster with two people digging."

r tint::quote_footer('--- Joe Martin')

Without using quote_footer(), it looks like this (the second line is just a normal paragraph):

"Great people talk about ideas, average people talk about things, and small people talk about wine."

--- Fran Lebowitz

Responsiveness

The HTML page is responsive in the sense that when the page width is smaller than 760px, sidenotes and margin notes will be hidden by default. For sidenotes, you can click their numbers (the superscripts) to toggle their visibility. For margin notes, you may click the circled plus signs to toggle visibility.

More Examples

The rest of this document consists of a few test cases to make sure everything still works well in slightly more complicated scenarios. First we generate two plots in one figure environment with the chunk option fig.show = 'hold':

p <- ggplot(mtcars2, aes(hp, mpg, color = am)) +
  geom_point()
p
p + geom_smooth(method="loess", span=0.8)

Then two plots in separate figure environments (the code is identical to the previous code chunk, but the chunk option is the default fig.show = 'asis' now):

You may have noticed that the two figures have different captions, and that is because we used a character vector of length 2 for the chunk option fig.cap (something like fig.cap = c('first plot', 'second plot')).

Next we show multiple plots in margin figures. Similarly, two plots in the same figure environment in the margin:

p
p + geom_smooth(method = 'loess', span=0.8)

Then two plots from the same code chunk placed in different figure environments:

knitr::kable(head(iris, 15))
p
knitr::kable(head(iris, 12))
p + geom_smooth(method = 'loess', span=0.8)
knitr::kable(head(iris, 5))

We blended some tables in the above code chunk only as placeholders to make sure there is enough vertical space among the margin figures, otherwise they will be stacked tightly together. For a practical document, you should not insert too many margin figures consecutively and make the margin crowded.

You do not have to assign captions to figures. We show three figures with no captions below in the margin, in the main column, and in full width, respectively.

# a boxplot of weight vs transmission; this figure
# will be placed in the margin
ggplot(mtcars2, aes(am, wt)) + geom_boxplot() +
  coord_flip()
# a figure in the main column
p <- ggplot(mtcars, aes(wt, hp)) + geom_point()
p
# a fullwidth figure
p + geom_smooth(method = 'loess', span=0.8) + facet_grid(~ gear)

Some Notes on Tufte CSS

There are a few other things in Tufte CSS that we have not mentioned so far. If you prefer r sans_serif('sans-serif fonts'), use the function sans_serif() in tufte. For epigraphs, you may use a pair of underscores to make the paragraph italic in a block quote, e.g.

I can win an argument on any topic, against any opponent. People know this, and steer clear of me at parties. Often, as a sign of their great respect, they don't even invite me.

r quote_footer('--- Dave Barry')

We hope you will enjoy the simplicity of R Markdown and this R package, and we sincerely thank the authors of the Tufte-CSS and Tufte-LaTeX projects for developing the beautiful CSS and LaTeX classes. Our tufte package would not have been possible without their heavy lifting.

To see the R Markdown source of this example document, you may follow this link to Github, use the wizard in RStudio IDE (File -> New File -> R Markdown -> From Template), or open the Rmd file in the package:

file.edit(
  tint:::template_resources(
    'tint', '..', 'skeleton', 'skeleton.Rmd'
  )
)
# create a bib file for the R packages used in this document
knitr::write_bib(c('base', 'rmarkdown'), file = 'skeleton.bib')

Add_shiny with browsable

Based on this http://timelyportfolio.github.io/sunburstR/example_baseball.html example (use sunburst event), I want to wrapped it into a shiny app, while from the CRAN, it used

add_shiny(sunburst=NULL),

From the example, it seems the argument should be a sunburst event; while I am wondering how to incorporate

browsable( tagList(sb, ...) )

into the shiny app, since the above code will not induce a sunburst event.

Thanks a lot,
Selina

Clarify documentation of colors parameter

I use csv data to create a sunburst diagram, but I cannot figure out how to assign colors to the individual elements. The documentation for sunburst's color argument recommends that I either supply a 'vector of strings representing colors as hexadecimal for manual colors' or if I wanted 'precise control of colors, supply a list with range and/or domain'.

Can somebody provide more detail on how to add colors?

Specifically, if I supply a vector, how will the elements of the vector be used, and if I supply a list, what do I have to supply as range or domain?

Return instance

Hello,
First of all, believe it or not - I am a big fan of your work. In recent months I have been starting to create my own widgets at work and I have been following yours as inspiration!

Question ( not an issue, just a curiosity) : why do you return the instance at line 552 of sunburst.js? Instance is not already defined in the factory and reassigned in the renderValue?

Probably I ask it since to me the receiver of the object {Rendervalue:...,Resize:..} is black magic :-)

Thanks,
Giovanni

Legend names being cutoff in the output.

I'm wondering if the breadcrumb feature for the path sequences, could also be applied for the legends or is there another way so that the names in the legend doesn't cutoff?

Also is there a way to show the legends by default?

features/ideas from blog comment

@markriseley suggested in comments to the blog post. This issue will track progress on his good ideas.

Thanks it's great to see this!

A couple of suggestions for making this really sharp for all-purpose use (which push beyond the original JS I know):

1) Supply an optional legend order argument vector eg c("home", "about"....)
2) Supply your own colour palette, mapped to the legend order if given (eg vector of hex codes)
3) Add a parameter 'centreText' which allows you to supply additional span text eg paste0(percentage, " of visits started with this sequence") inside the circle
4) Optionally (as a default) suppress "root" node from legend and colour scale calculations (as I don't think it would ever have a value?). Currently it clutters the legend with no purpose.

I wish I knew a bit more JavaScript so I could do this myself. Keep up the good work!

The "-end" marker is being included in the path sequence output.

The "-end" marker is being shown in my chart. Based on Kerry Rodden's CSV format instructions, shouldn't the '-end" marker just serve as an indicator to distinguish a true end point? I believe the last path sequence to be shown should be the one before the "-end" marker.

If this is not an error. Is there a way to hide the "-end" marker and remove it from the path sequence? Initially I tried to run the data without the "-end" marker, but it doesn't render the chart without it.

You can view a sample of my data here:
https://github.com/jrangeles/Path-Sequence/blob/master/sequences_overview.csv

checklist for V1 on CRAN

  • increment version in DESCRIPTION
  • update NEWS.md
  • run CRAN checks locally and with travis, win-builder, and rhub
  • submit to CRAN

NA handling

I have two CSV files with sequences that I want to input into sunburstR. The first is structured like this:

                                                   drugs   proportion
1                                    metformin-NA-NA-NA-NA 0.2963424402
2                             insulin glargine-NA-NA-NA-NA 0.0697695114
3                                    glipizide-NA-NA-NA-NA 0.0346622764
[...]
78  insulin aspart-insulin glargine-insulin isophane-NA-NA 0.0017353386
79            glimepiride-metformin-insulin glargine-NA-NA 0.0014906114
80         insulin glargine-metformin-insulin aspart-NA-NA 0.0014238676

This first file works fine, however the NA values are displayed as their own string. I simply removed them and have a new file structured like this:

                                               drugseq   proportion
1                                            metformin 0.2963424402
2                                     insulin glargine 0.0697695114
3                                            glipizide 0.0346622764
[...]
78    insulin aspart-insulin glargine-insulin isophane 0.0017353386
79              glimepiride-metformin-insulin glargine 0.0014906114
80           insulin glargine-metformin-insulin aspart 0.0014238676

This file runs without any errors in sunburstR, but there is no graphical output at all. I've been struggling with this for hours and can't figure out what is going on. Can you help me? I have attached sample CSVs.

Thanks,
Kipp

example_csv.zip

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.