How to include ggplotly figures in a html report using R Markdown - html

I cannot include plotly figures in a html report in R markdown when the figures are generated from a function.
I can obtain ggplotly figures in a html report in R markdown when ploting them directly without any functions. For instance, kniting the example below:
a <- ggplot(Data, aes_string(x="Category", y=Phenotype)) + geom_violin() + geom_boxplot()
plot(a)
ggplotly(a)
However, when I try to include the graph in a function in order to obtain many graphs from different phenotypes, the figures don't appear in the html report.
Do_graph=function(Data, Phenotype){a<- ggplot(Data, aes_string(x="Category", y=Phenotype)) + geom_violin() + geom_boxplot()
plot(a)
ggplotly(a)}
Phenotypes<-c("A","B","C")
for(Phenotype in Phenotypes){Do_graph(Data, Phenotype)}
Does anyone know how to solve this problem? I've seen some similar issues related to html.widget but I couldn't fix it. Thank you

Related

how to save the generated images from this code separated

I have run StarGAN Code from github, this code generate all the generated images in one picture.
How I can save all the generated images separated to single folder? I do not want to save all the images in one picture.
this is how it generate the output (sample image
I want to save the generated images from the trained model, not as samples with all the images in one picture but just a file that contains all the generated images.
This is the part of the code i want to change it
# Translate fixed images for debugging.
if (i+1) % self.sample_step == 0:
with torch.no_grad():
x_fake_list = [x_fixed]
for c_fixed in c_fixed_list:
x_fake_list.append(self.G(x_fixed, c_fixed))
x_concat = torch.cat(x_fake_list, dim=3)
sample_path = os.path.join(self.sample_dir, '{}-images.jpg'.format(i+1))
save_image(self.denorm(x_concat.data.cpu()), sample_path, nrow=1, padding=0)
print('Saved real and fake images into {}...'.format(sample_path))
The generator self.G is called on each element of c_fixed_list to generate images. All results are concatenated, then saved using torchvision.utils.save_image.
I don't see what's holding you from saving the images inside the loop. Something that would resemble:
for j, c_fixed in enumerate(c_fixed_list):
x_fake = self.G(x_fixed, c_fixed)
for k in range(len(x_fake)):
sample_path = os.path.join(self.sample_dir, f'{i+1}-{k}-feat{j}-image.jpg')
save_image(self.denorm(x_fake.data[k].cpu()), sample_path, nrow=1, padding=0)

SSRS - Multiple font or color within a chart item

I'm using Report Builder 3.0. Long story short, I want to make the font bold for the text in the red box that you see in the image below:
Basically, it's just one expression in the legend field of my value, however, for clarity's sake (for my end users) I wish to make the "title part" bold. I found the following solution for textboxes in a tablix using Html by checking off the "HTML – Interpret HTML tags as styles." checkbox within the Textbox's properties. (http://www.sqlchick.com/entries/2010/10/31/using-different-formats-within-a-single-textbox-in-ssrs.html)
However, I can't find anything similar for graphs! I mean if MS thought about it for tables, I presume they must've given it some thought for a chart setting too.
Thanks to all!
p.s. As an aesthetic solution to my problem, I did think of simply creating a new title field, moving it to the exact same location and formating it. But I'm surious whether there'd be some more "proper" way of doing this.
I'm using the same approach for one of my charts.
STEPS.
Select the Chart series to open property pane. In my case, the chart series name is TWR Chart Series
Select the color property and select to build the expression.
I'm posting one of my expression. You can build your own expression base don your field names etc.
=IIF(Fields!ProductID.Value = 1 OR Fields!ProductID.Value = 6,"#00425E",
IIF(Fields!ProductID.Value = 3 ,"#6B8797",
IIF(Fields!ProductID.Value = 5 OR Fields!ProductID.Value = 7,"#799179",
IIF(Fields!ProductID.Value = 4 AND Fields!sort.Value=99,"#6bb1be","#48597B"))))
If used sensibly, you should get your desired results.Good luck.

In R package Formattable, how to apply digits and conditional formatting at the same time?

I have the object TABLE_LIST which is a list that has tables (I can't provide the contents for privacy policies, sorry).
I first created the object TABLE_LIST (It is a list of data.frames 2x12)
TABLE_LIST=lapply(1:4, function(x) data.frame(rbind(total.ratio4[[x]][-(1)], total.ratio2[[x]][-(1)]), row.names=row))
The following code gives me red and green font colors based on the value on the cell, and it works like a charm:
formattable(TABLE_LIST[[1]], list(area(,-(c(5,10)))~formatter("span", style=x~style(color=ifelse(x>1,"red","green"))),area(,(c(5,10)))~formatter("span", style=x~style(color=ifelse(x>1,"green","red")))))
However, I need COLOR AND comma separated numbers. My failed attempt is:
formattable(TABLE_LIST[[1]], list(area(,-(c(5,10)))~formatter("span", style=x~style(color=ifelse(x>1,"red","green"))),area(,(c(5,10)))~formatter("span", style=x~style(color=ifelse(x>1,"green","red"),digits(x,2))),
area(1:2,1:10)~formatter("span",x~ style(digits(x,2)))))
This code works well, but erases the formatting of the color. I do not know what else to do.
I have to mention I cannot change the original data.frame without messing everything up. So I gotta make the changes on table_list or formattable. Thank you.
I think I solved it. So I will share this small knowledge to people who may have the same problems as me:
formattable(TABLE_LIST[[1]],
list(
area(,-(c(5,10)))~formatter("span",
style=x~style(color=ifelse(x>1,"red","green")),
x~style(digits(x,4))),
area(,(c(5,10)))~formatter("span",
style=x~style(color=ifelse(x>1,"green","red")),
x~style(digits(x,4)))))
Basically, inside the same formatter, on the level of style, add a comma and x~style.

how to add line chart in October CMS?

I want to add a line chart as a control chart in one of the widget pages in October CMS. CMS has pre-built classes for bar chart and pie chart. I was wondering if they have similar classes for other kind of analytics data.
I want to add the line chart prebuilt class to an html partials page, that can be used as a widget in october cms.
It seems that you are talking about things like this: https://octobercms.com/docs/ui/chart and you are looking for another type of chart besides those mentioned there.
I wanted to say if such a thing is not listed there then probably it does not exist. But... hey... I just went looking into the backend UI JS code.
Look at this file in your October app root: {% app root %}/modules/system/assets/ui/js/chart.line.js
/*
* Line Chart Plugin
*
* Data attributes:
* - data-control="chart-line" - enables the line chart plugin
* - data-reset-zoom-link="#reset-zoom" - specifies a link to reset zoom
* - data-zoomable - indicates that the chart is zoomable
* - data-time-mode="weeks" - if the "weeks" value is specified and the xaxis mo
de is "time", the X axis labels will be displayed as week end dates.
* - data-chart-options="xaxis: {mode: 'time'}" - specifies the Flot configurati
on in JSON format. See https://github.com/flot/flot/blob/master/API.md for detai
ls.
*
* Data sets are defined with the SPAN elements inside the chart element: <span
data-chart="dataset" data-set-data="[0,0],[1,19]">
* Data set elements could contain data attributes with names in the format "dat
a-set-color". The names for the data set
* attributes are described in the Flot documentation: https://github.com/flot/f
lot/blob/master/API.md#data-format
*
* JavaScript API:
* $('.chart').chartLine({ resetZoomLink:'#reset-zoom' })
*
So the functionality is there, it seems, but it's not in the public docs. Looks like you could try out something like this
<div
class="control-chart"
data-control="chart-line"
style="min-height:400px"
data-zoomable="1"
data-reset-zoom-link="#reset-zoom"
data->
<span data-chart="dataset" data-set-label="Graph me tender" data-set-data="[0,0],[1,5],[3,8],[4,2],[5,6]">
Graph me tender
</span>
<span data-chart="dataset" data-set-label="Graph me sweet" data-set-data="[0,0],[1,5],[3,8],[4,2]">
Graph me sweet
</span>
</div>
<a id="#reset-zoom" href="#">Reset zoom</a>
(Edit: There was a somewhat "dirty" tweak necessary here: I added a min-height css attribute, otherwise there was an error thrown. Maybe there should be some additional class for that instead which I do not know. Also, the two data-sets are not plotted in order (the second is plotted first) and are wrongly labeled in the legend, and appear horizontally connected to each other. The zoom function does not seem to work, etc, etc. I think this line graph thingy is possibly still work in progress and that might be the reason why it is not included in the docs yet. )
, play around with it and see what it does. (I have not tested this and hope it works somehow.) If I understand correctly it should give you a zoomable line graph with data points [0,0],[1,5],[3,8],[4,2],[5,6] (x,y coordinate points) and the link below should reset the zoom (edit: zooming does not work. maybe need to set some additional options for that)
The whole thing seems to be based on this Flot JQuery chart library. So you might find some good further hints there or here, besides reading October's {% app root %}/modules/system/assets/ui/js/chart.line.js source code.

R Markdown HTML Number Figures

Does anyone know how to number the figures in the captions, for HTML format R Markdown script?
For PDF documents, the caption will say something like:
Figure X: Some Caption Text
However, the equivalent caption for the HTML version will simply say:
Some Caption Text
This makes cross-referencing figures by number completely useless.
Here is a minimal example:
---
title: "My Title"
author: "Me"
output:
pdf_document: default
html_document: default
---
```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```
```{r cars2, fig.cap = "Another amazing plot"}
plot(cars)
```
I have tried setting toc, fig_caption and number_sections within each of the output formats, but this does not seem to change the result.
The other answers provided are relatively out of date, and this has since been made very easy using the bookdown package. This package provides a number of improvements which includes the built-in numbering of figures across Word, HTML and PDF.
To be able to use bookdown, you need to first install the package install.packages("bookdown") and then use one of the output formats. For HTML, this is html_document2. Taking your example:
---
title: "My Title"
author: "Me"
date: "1/1/2016"
output: bookdown::html_document2
---
```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```
```{r cars2, fig.cap = "Another amazing plot"}
plot(cars)
```
These Figures will be numbered Figure 1 and Figure 2. Providing the code chunk is named and has a caption, we can cross reference the output using the the syntax \#ref(fig:foo) where foo is the name of the chunk i.e. \#ref(fig-cars). You can learn more about this behaviour here
Further Reading
R Markdown: The definitive Guide: Chapter 11 provides a great overview of bookdown
Authoring books with bookdown provides a comprehensive guide on bookdown, and recommended for more advanced details.
So unless someone has a better solution, this is the solution that I came up with, there are some flaws with this approach (for example, if the figure/table number is dependent on the section number etc...), but for the basic html document, it works.
Somewhere at the top of you document, run this:
```{r echo=FALSE}
#Determine the output format of the document
outputFormat = opts_knit$get("rmarkdown.pandoc.to")
#Figure and Table Caption Numbering, for HTML do it manually
capTabNo = 1; capFigNo = 1;
#Function to add the Table Number
capTab = function(x){
if(outputFormat == 'html'){
x = paste0("Table ",capTabNo,". ",x)
capTabNo <<- capTabNo + 1
}; x
}
#Function to add the Figure Number
capFig = function(x){
if(outputFormat == 'html'){
x = paste0("Figure ",capFigNo,". ",x)
capFigNo <<- capFigNo + 1
}; x
}
```
Then during the course of your document, if say you want to plot a figure:
```{r figA,fig.cap=capFig("My Figure Caption")
base = ggplot(data=data.frame(x=0,y=0),aes(x,y)) + geom_point()
base
```
Substitute the capFig to capTab in the above, if you want a table caption.
We can make use of pandoc-crossref, a filter that allows a cross-referencing of figures, tables, sections, and equations and works for all output format. The easiest way is to cat the figure label (in the form of {#fig:figure_label}) after each plot, although this requires echo=FALSE and results='asis'. Then we can reference a figure as we would a citation : [#fig:figure_label] produces fig. figure_number by default.
Here is a MWE:
---
output:
html_document:
toc: true
number_sections: true
fig_caption: true
pandoc_args: ["-F","pandoc-crossref"]
---
```{r}
knitr::opts_chunk$set(echo=FALSE,results='asis')
```
```{r plot1,fig.cap="This is plot one"}
x <- 1:10
y <- rnorm(10)
plot(x,y)
cat("{#fig:plot1}")
```
As we can see in [#fig:plot1]... whereas [#fig:plot2] shows...
```{r plot2, fig.cap="This is plot two"}
plot(y,x)
cat("{#fig:plot2}")
```
which produces (removing the graphics
PLOT1
Figure 1: This is plot one
As we can see in fig. 1… whereas fig. 2 shows…
PLOT2
Figure 2: This is plot two
See the pandoc-crossref readme for more options and customizations.
To install pandoc-crossref, assuming you have a haskell installation:
cabal update
cabal install pandoc-crossref
I solve cross-referencing using a solution similar to that posted by Nicholas above. I use bookdown for some projects but I find that awkward to use for other projects where I just want simple cross-referencing.
I use the following when I am writing a paper with rmarkdown and I want it in standard format for submission to a journal. I want a figure legend at the end, then tables, then I'll have the tables and figures. As I am writing, I only have a rough idea of what order the figures will be referenced in the text. I just want to reference them with a text code like fig:foobar and have the number assigned based appearance in the text. When I look at the figure legend list, I'll see what order to put the legends and will move legends around as needed.
Here's my structure.
I have an R package where I have things I need for papers, like various bibliographies and helper R functions. In that package, I have the following function which uses some variables defined in the main Rmd environment: .rmdenvir and .rmdctr .
ref <- function(useName) {
require(stringr)
if(!exists(".refctr")) .refctr <- c(`_` = 0)
if(any(names(.refctr)==useName)) return(.refctr[useName])
type=str_split(useName,":")[[1]][1]
nObj <- sum(str_detect(names(.refctr),type))
useNum <- nObj + 1
newrefctr <- c(.refctr, useNum)
names(newrefctr)[length(.refctr) + 1] <- useName
assign(".refctr", newrefctr, envir=.rmdenvir)
return(useNum)
}
It assumes that I name things I want referenced with something like cntname:foo, for example fig:foo. It makes a new counter for each one and I can make up new counters on the fly (while writing) if needed.
In my main Rmd file, I have some set-up lines:
```{r setup_main}
require(myPackageforPapers)
# here is where the variables needed by ref() are defined.
.rmdenvir = environment()
.refctr <- c(`_` = 0)
````
In the text I use the following
You can see what I am trying to show in Figure `r ref("fig:foo")`
and you can see it also in Tables `r ref("tab:foo")`
and A`r ref("tabappA:foobig")`.
to get "You can see what I am trying to show in Figure 1 and you can see it also in Tables 1 and A1." Although the numbers might not be 1; the number to use will be dynamically determined. I don't have to use a special function for the first time I reference a figure, table or whatever I am counting. ref() figures that out by looking to see if the label exists already. If not it assigns the next number, and returns it. So you don't have to use "label" in one place and "ref" in another.
In the course of writing, I might decide that appendix A is getting too big, and that I will split off some of the tables into an appendix B. All I need to do is change the above to
You can see what I am trying to show in Figure `r ref("fig:foo")`
and you can see it also in Tables `r ref("tab:foo")`
and B`r ref("tabappB:foobig")`.
I just specify a new counter name 'tabappB' and the numbers for that are dynamically determined.
At the end of my Rmd file, I have a figure list that will look like
# Figure Legends
Figure `r ref("fig:foo")`. This is the legend for this figure.
Figure `r ref("fig:foo2")`. This is the legend for another figure.
Then my tables appear like so
```{r print-tablefoo, echo=FALSE}
tablefoo=mtcars
thecap = "Tables appear with a legend while figures do not."
fullcap = paste("Table ", ref("tab:foo"), ". ", thecap, sep="")
kable(tablefoo, caption=fullcap)
```
and then the figures like so:
```{r fig-foo, echo=FALSE, fig.cap=paste("Figure",ref("fig:foo"))}
plot(1,1)
```
Appendix A is an Rmd file that included as a child. It will have tables like
```{r print-tableAfoo, echo=FALSE}
tablefoo=mtcars
thecap = "This is a legend."
fullcap = paste("Table A", ref("tabappA:foobig"), ". ", thecap, sep="")
kable(tablefoo, caption=fullcap)
```
I do have to add the "A" to get Table A1, but I find it easier if R doesn't think too much for me in terms of labelling my counters. I just I want it to return the right number.
The cross-referencing works for html, pdf/latex or word. I'd happily stick with latex solutions, but my co-authors use word so I need a solution that works with pandoc and word. Also sometimes I want html or some other output and I need a solution that works for any output that works with rmarkdown.