How to embed a plotly graph on a wordpress website? - r

I am trying to embed a plotly graph I created in R on a wordpress website. It seems a lot more difficult than it should. Perhaps I am missing something obvious. Here is what I tried:
solution 1: saved the graph as an html using htmlwidgets::saveWidget(as_widget(Basic_Spending_Graph), file = "Basic_Spending_Graph.html"). Then use that html to either embed the whole file or html source code into the website. There are numerous problems with this approach. Firstly if I embed file it embeds a link to the file where you can open the page rather than fully embedding the graph within the page. Secondly the file is 3 Mbs, which over time could put a strain on website speed which is using shared hosting.
solution 2: export plotly graphs from R to chart studio which allows you to host graph on their server and generate an html embedding snippet. This seems like a great solution, but I am struggling to find an easy way to export from R to chart studio, since I already spent quite a lot of time creating the graphs in R. Apparently there is a way to export the charts to chart studio, but nobody seems to explain how?
I may be missing something very obvious considering plotly was designed with web in the mind! Any advice would be greatly appreciated. What is the best way of getting plotly charts on the webpage?
Thanks!

I can't help you with solution 1, but re: solution 2, while this is maddening to find, there is actually a pretty simple solution.
First, you need to register with chart studio online and generate your api key. For whatever reason, to generate your api key you need to view your "settings." (see here: https://chart-studio.plotly.com/settings/api)
Once you've got your api key, you can run the following code from R and it will upload your plotly chart to your profile.
#first we register to upload to plotly
key <- readLines("path/to/your/api/key")
Sys.setenv("plotly_username"="<your username>")
Sys.setenv("plotly_api_key"=key)
#now we post to plolty
plotly_POST(
x = last_plot(),
file = "<whatever you want to name your plot>",
fileopt = "overwrite",
sharing = c("public"),
world_readable=TRUE
)
#note that evidently, plotly_POST is depreciated, though it worked for me as of 11/2020
#use instead the call below, with the same arguments
api_create(
x = last_plot(),
file = "<whatever you want to name your plot>",
fileopt = "overwrite",
sharing = c("public"),
world_readable=TRUE
)

Related

Error in excel charts when overwrite data from R

I am trying to automate some of my tests in R to produce a static report in Excel. I have created a template in Excel which has a few charts and tables(sheet 1).
Now I run my R code to generate the data to fill in the same excel template file on Sheet 2.
I am using Openxlsx package to loadworkbook(excel template), next I overwrite data in sheet 2 by deleting the sheet and recreating it again with the new data so that the excel template has data for new test runs.
This runs without any error. But when I open my excel back the charts disappear with the !REF# error whereas as the tables are overwritten properly in the template(sheet1).
Has anyone come across such a scenario? The method I am using is a bit weird but can't think of any other alternative.
Thanks in advance!!
This definitely sounds weird. Something seems off, but I'm sorry I can't tell you what the issue may be. Anyway, I would say, just use R to generate the data and dump everything into Excel. Then, run some VBA in Excel to create the charts. I have no idea what your VBA skills are like, but I'm guessing it would be much easier to crate charts in Excel using VBA, rather than trying to do all of this with R.
Here are a few resources that you may find useful.
https://www.thespreadsheetguru.com/blog/2015/3/1/the-vba-coding-guide-for-excel-charts-graph
https://analysistabs.com/excel-vba/chart-examples-tutorials/
http://www.sthda.com/english/wiki/r-xlsx-package-a-quick-start-guide-to-manipulate-excel-files-in-r
Finally, you can learn a lot by recording Macros and hitting F8 to step-through the code to see how everything works.

Displaying png files from R into spotfire

I want to pass data from Spotfire to R and then display the plot constructed by R.
What is the best way to do this?
I’ve figured out the trick of putting images into Spotfire. It’s not hard if you follow these directions, but it’s done in a way very different from how you guess you would do it in Spotfire, and that’s why it took me awhile to figure out.
Here’s an overview of how to do it. You create a DocumentProperty which is a binary object, you write some Spotfire code that gives a value to that Document Property, and you display that binary object using a Spotfire Property Control of the “Label” type.
The confusing parts are that you DON’T use the Spotfire “Insert Image” tool at all, and that you DON’T use the filename generated inside the R code in Spotfire at all. Once you get used to the idea that the two most obvious ways you think you would approach the problem in Spotfire are entirely useless and wrong, you can make some progress.
I’ll leave out the spiderplot specifics because the code’s pretty long.
Here’s what you do.
1) Create a document Property in Spotfire of type “Binary”, e.g., “imageThatGoesBackToSpotfire”
2) You write some R code that generates an image and writes it to a file:
# get a temporary directory name on the local machine. You wouldn’t need to do this is you were just
# going to run it on your own, but you need to do it if you intend to let anybody else run it on their own machine.
tempfilebase = tempfile()
# take the tempfilebase and prepend it to a filename.
myFilename<-“someFileName.jpg”
myFullFilename <- paste(tempfilebase,myFilename,sep="")
#open a jpeg
jpeg(filename=myFullFileName)
# generate the image, however you normally would in R
plot(input)
# close the file
dev.off
# open a connection to that file.
myConnection<-file(myFullFileName,open=”rb”)
imageThatGoesBackToSpotfire<- data.frame(r=readBin(myConnection, what="raw", n=(file.info(myFullFileName)$size)))
close(myConnection)
3) Run your R script, above. Select some columns that are the “input” to the plot, and make the R script return outputs to the “imageThatGoesBackToSpotfire” DocumentProperties.
4) Create a text area in Spotfire.
5) Insert a Property Control into the text area of type “label”. (Click on the icon that’s circled in the picture below). This opens a dialog,
You need to register a data function with inputs and outputs, and the specific PNG data needs to be returned as a binary label.
Some details: http://spotfire.tibco.com/tips/2014/02/25/dynamically-displaying-images-in-a-text-area/

Redirecting R graphs to MS Word

I wonder how to redirect R graphs to MS Word? Like sink() redirect the R output to any file but not the graphs. I tried R2Wd but sometimes it doesn't work properly. Any comment and help will be highly appreciated. Thanks
To answer your direct question, the best way to get the results of R scripts and plots into word is probably via some form of Sweave. Look up odfweave to send R output to a LibreOffice file that can then be converted to word, or even opened directly in Word if you have the right plugin.
To create plots that can be editable (i.e you can alter the look of plots, move the legend etc) I would recommend saving the plot to an svg format (scalable vector graphic) that you can then edit using the excellent free vector graphics app inkscape.
For instance, if I create my ggplot2 graph as an object
library(ggplot2)
dataframe<-data.frame(fac=factor(c(1:4)),data1=rnorm(400,100,sd=15))
dataframe$data2<-dataframe$data1*c(0.25,0.5,0.75,1)
testplot<-qplot(x=fac, y=data2,data=dataframe, colour=fac, geom=c("boxplot", "jitter"))
You can use the Cairo package, which allows creation of svg files, I can then edit these in Inkscape.
library(Cairo)
Cairo(600,600,file="testplot.svg",type="svg",bg="transparent",pointsize=8, units="px",dpi=400)
testplot
dev.off()
Cairo(1200,1200,file="testplot12200.png",type="png",bg="transparent",pointsize=12, units="px",dpi=200)
testplot
dev.off()
For more info read this previous question that has more good answers Create Editable plots from R
Also, you can follow this advice from Hadley, and save the actual ggplot2 object, then load it later and modify it
save(testplot, file = "test-plot.rdata")
# Time passes and you start a new R session
load("test-plot.rdata")
testplot + opts(legend.position = "none")
testplot + geom_point()
To get sink() like behavior with MSword look at the wdTxtStart function in the TeachingDemos package. This uses R2wd internally, so you will see similar functionality, this just sends everything you do to the word document.
Graphs are not sent automatically since you may be adding to them, but once you know you are finished with the graph you can use wdtxtPlot to send the current graph to the word document.
If you know what you want to do ahead of time then sweave or something similar is probably the better approach (as has already been mentioned). The group that created Rexcel are also working on Sword that does sweave like things within MSword.

Embedding googleVis charts into a web site

Reading from the googleVis package vignette: "With the googleVis package users can create easily web pages with interactive charts based on R data frames and display them either via the R.rsp package or within their own sites". Following the instructions I was able to see the sample charts, using the plot method for gvis objects. This method by default creates a rsp-file in the rsp/myAnalysis folder of the googleVis package, using the type and chart id information of the object and displays the output using the local web server of the R.rsp package (port 8074 by default).
Could anybody help me (or provide some link) on the procedure someone has to follow in order to embed such charts into an existing web site (e.g. a joomla site)?
Obviously I think that this is too verbose for #gd047, but I put a kind of tutorial since it maybe helpful for other readers who want to use googleVis on their own website.
install googleVis from CRAN
install.packages('googleVis')
pay attention to the messages.
then, create gvis object:
library(googleVis)
M <- gvisMotionChart(Fruits, "Fruit", "Year")
you can find the contents of M by:
> M
and you can find the plot on your browser:
> plot(M)
then, what is necessary to generate the chart is M$html$chart:
> M$html$chart
[1] "<!-- MotionChart ... omitted... \">\n</div>\n"
save it to a file:
> cat(M$html$chart, file="tmp.html")
if you open the "tmp.html" as a file (i.e, address says files:///***/tmp.html), then security warning may occur. What you need is to access the html via http://.
So if you can edit any web page where <script> tag is available (e.g., blogger), you can use it by simply copy and paste the contents of tmp.html, like this:
http://takahashik.blogspot.com/2011/01/googlevis-example.html
here is the famous "iris" version of example:
http://takahashik.blogspot.com/2011/01/googlevis-example-for-data-iris_10.html
Otherwise, if you have a web server, you can use it by uploading the tmp.html on the server.
If you want to copy and paste the chart manually to a CMS (e.g. Joomla/Wordpress site), than you could do it from the 'gvis' object's html list. Just like #kohske suggested:
# demo data from manual
M <- gvisMotionChart(Fruits, "Fruit", "Year")
# write the HTML body to a temporary file without header and footer
cat(M$html$chart, file="temp.html")
# or with caption included:
cat(paste(M$html[c("chart", "caption")], collapse="\n"), file="temp.html")
Then copy and paste the content of temp.html to your Joomla site. You should pay attention to paste the code as HTML content, not in the WYSIWYG editor (e.g. Tiny MCE)!
If you want to show it on a separate page, do not forget to include header and footer also:
# demo data from manual
M <- gvisMotionChart(Fruits, "Fruit", "Year")
# write the HTML to a temporary file with header and footer all included
cat(paste(M$html, collapse="\n"), file="temp.html")
And at last: you can easily upload this document to e.g. an ftp server and reach it via any browser.
Flash content might not work on local machine. I had to change the security restrictions on adobe site in order to make it work.
Now, by following daroczig's instructions one can view the content in the local browser and do not rely on R.rsp altogether.
You could alternatively write the following code
print(M,"chart", file="myfile")
copy and paste the html output to your webpage and the googleVis chart will run
I have a script to run automatically as data updates and place a googleVis chart on a website using RCurl and googleVis. Here is an example where visChart is the chart:
library(RCurl)
library(googleVis)
make visChart
write(visChart$html$chart, file='visChart.html')
ftpUpload('visChart.html', "ftp://username:password#example.com/path/to/'visChart.html")
visChart$html$chart gives just the html for just the chart with out the footer so then I use an iframe in my HTML to access this chart. If you are using a google site, blogger or want a google gadget you can use createGoogleGadget():
write(createGoogleGadget(visChart), file='visChart.xml')
ftpUpload('visChart.xml', "ftp://username:password#example.com/path/to/'visChart.xml")

how to make jmeter output graphs

I am not a jmeter expert, but I understand it can display graphs and save the data in .xml files.
Is there a way to have jmeter actually create JPG, GIF or PNG files (or whatever format that can be embedded in html?)
Added later: I need a solution that works in a batch run
A simple way would be to right click on a Graph Result to "Save Node as Image".
Use Loadosophia or jmeter-plugins
I would stand by #Andrey Pohilko in agreeing that Loadosophia is the best when it comes to graphs and also jmeter-plugins for addons for jmeter tool.
Check out the sample loadosophia graph here.
I would suggest saving as a CSV file, then using a graphing engine separately to generate graphs. If you want to create them dynamically you could use some open-source graphing tools and a workflow engine.
If you're happy with doing it by hand, Excel?
there is a list of ways to analyze logs on the wiki - http://wiki.apache.org/jakarta-jmeter/LogAnalysis
I use jmetergraph.pl for nice summary reports.
Note that there is a bug with the default jmetergraph.pl, you need to add this to line 313, at the end of the while loop:
close(IN);
}
$glabels{'entire'} = \%entire; # this line added.
print "Found $#labels labels\n" if $DEBUG;
Otherwise you can use the jmeterlog class to create your own images by writing custom code for it.....
Use JMeter-plugins and the listener called JP#GC Graphs Generator:
http://www.ubik-ingenierie.com/blog/automatically-generating-nice-graphs-at-end-of-your-load-test-with-apache-jmeter-and-jmeter-plugins/
In upcoming version 2.14 or 3.0, there will be this new feature that generate an HTML report with dynamic graphs, APDEX table and summary of errors:
http://jmeter.512774.n5.nabble.com/Donation-of-a-New-Dashboard-for-JMeter-Questions-and-more-td5723379.html
It is available in nightly build as of 20th january 2016:
http://jmeter.apache.org/nightly.html

Resources