My sample dataset:
library(plotly)
library(htmlwidgets)
d <-
data.frame(
"name" = c("bily", "mary", "ken"),
"fruit" = c("cherry", "apple", "apple"),
"count" = c(1, 10, 30)
)
gg <- ggplot(data = d,
aes(x = fruit,
y = count,
group = name)) +
geom_line(aes(color = name)) +
geom_point(aes(color = name))
plotly <- ggplotly(gg)
save graph:
d <- # please put your directory where you want to save the graph
"xxxx/graph.html"
I have searched these three functions that can output the HTML format but they will also make other files and I cannot solve it.
#htmlwidgets::saveWidget(as_widget(plotly), d)
#htmltools::browsable(plotly)
htmltools::save_html(plotly, d)
I am trying to convert my graph, which uses from ggplot function to ggplotly function, to HTML format but I face a problem. When I save the graph, the function will also make other files such as plotlyjs, jquery, and crosstalk. I hope only the HTML file can be made because it is too hard to put the files on the website if each graph has different files.
These are the files when I run the code. My expected result is that only the HTML file is made.
The other files are saved in the directory of the lib but I hope they are not provided and I can run the HTML file. Is it possible to do? or Are there any other methods?
Just add selfcontained = TRUE to your last line:
htmlwidgets::saveWidget(as_widget(plotly), selfcontained = TRUE, file = "xxxx/graph.html")
Related
I am scheduling R script which contains ggsave for saving pdf.
my code is running but on the line of ggsave("plot.pdf), it is skipping code. But instead of saving pdf if i use png format then it is fine. but only for pdf it is giving problem.
Below is my sample code.
library(ggplot2)
library(data.table)
a <- data.frame(a = c(1:5))
p <- ggplot(data.frame(x = 1:5, y = 1:5), aes(x, y)) + geom_point()
fwrite(a,"abc1.csv")
ggsave("plot.pdf")
Does ggsave(p, "plot.pdf", device = "pdf") work? You may not have been specifying the plot to be saved or perhaps it doesn't know to export as pdf from only the file path that you gave?
EDIT: It should be ggsave("plot.pdf", p, device = "pdf") so that the arguments are in the correct order.
I am working on a large shinydashboard and was keeping my code for modeling in a separate file from the main app.R. The problem is that I need to plot my data. This requires that I save my ggplots from one file and load them in my main app.R file. How can I save my ggplots and load them.
As a simple example lets say I have the following
#make plot
> p <- mtcars %>%
ggplot(aes(x = mpg, y = cyl))+geom_point()
#save plot
> save(file=here::here("plots/a_plot.Rdata"),p)
#load plot
> p <- load(file=here::here("plots/trans_arima.Rdata"))
> p
[1] "p"
How can I load my ggplot?
You can save your plot as a png file and then load it back into youyr file
you have several option for saving your plot. you could use ggplot2s' ggsave()
function or you could use the save_plot() from the cowplot package. save_plot() is said to
give you more flexibility when it comes file adjusting hence my pick.
You can explore both.
refer to https://rdrr.io/cran/cowplot/man/save_plot.html to read more about save_plot.
tmp = data.frame(first = c('a','b','c','d','e','f','g','h','i','j','k','l','m','n'),
second = c(2,3,4,5,2,3,4,5,6,3,4,4,6, 7))
plot_tmp = ggplot(tmp, aes(first, second)) + geom_bar(stat = 'identity')
dev.new()
if("png" %in% installed.packages()){
library(png)
}else{
install.packages("png")
library(png)
}
save_plot("~/plot_tmp.png", plot_tmp, base_height = NULL, base_aspect_ratio = 1.618,
base_width = 6)
Use the following steps to load files into your shiny using by using the
#read plot
library(OpenImageR)
img<-OpenImageR::readImage("~/plot_tmp.png")
imageShow(img)
Hopefully this helps. To read more about OpenImageR and how you can use it in shiny please go to https://cran.r-project.org/web/packages/OpenImageR/vignettes/The_OpenImageR_package.html
have fun!!!
I would like to display a plotly plot object in a standalone window that behaves similarly to the window that pops up using the base R plot() function.
Using a basic example from the plotly website:
library(ggplot2)
library(plotly)
d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- ggplot(data = d, aes(x = carat, y = price)) +
geom_point(aes(text = paste("Clarity:", clarity))) +
geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~ cut)
p2 <- ggplotly(p)
The p2 object is an htmlwidget object and I get some control over its display using the sizingPolicy element as described here. However, I can't find anything that allows me to set the viewer/browser to something other than my current browser (as a new tab) or within RStudio.
Ideally, I'd like to avoid applications outside of R packages to launch a separate window from within R. However, I would also be happy with figuring out how to granularly control browser output to display p2 as a new window in kiosk or app mode (see the answers to this question for some examples of kiosk/app mode).
Edit: Although I mentioned RStudio when discussing some of the options that I was able to find, I am talking about using R from a simple console. That said, granular display options should hopefully be independent of the user interface.
I have a working solution, but I'll be happy to change the accepted answer if someone has anything better.
I defined a print function that can be used to launch a custom browser command for an htmlwidget object. In this case, I used chromium-browser -app=..., but the overall approach should be general.
print_app <- function(widget) {
# Generate random file name
temp <- paste(tempfile('plotly'), 'html', sep = '.')
# Save. Note, leaving selfcontained=TRUE created files that froze my browser
htmlwidgets::saveWidget(widget, temp, selfcontained = FALSE)
# Launch with desired application
system(sprintf("chromium-browser -app=file://%s", temp))
# Return file name if it's needed for any other purpose
temp
}
Combining with the previous example:
library(ggplot2)
library(plotly)
d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- ggplot(data = d, aes(x = carat, y = price)) +
geom_point(aes(text = paste("Clarity:", clarity))) +
geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~ cut)
p2 <- ggplotly(p)
print_app(p2)
It seems like htmlwidgets normally uses the html_print function from htmltools, which in turn selects the browser to use via getOption("viewer", utils::browseURL), which bakes in a lot of the browser selection options -- making it challenging to change.
The idea for saving the html file locally came from this plotly issue: saving plotly plots locally?.
If you are using MacOS, change this line in #ssokolen's answer
# Launch with desired application
system(sprintf("chromium-browser -app=file://%s", temp))
to
system(sprintf("open -a 'google chrome' /%s", temp))
Works in zsh in MacOs Catalina with the Intellij R plugin.
I have csv files that each has multiple stack plot, but input csv files named with rather long character. However, in my resulted plot, full name of csv files not fully printed in facet_wrap which easily confused category of plot are referring to. I am trying to adjust the size of face_wrap by using space, scale parameter, but full name of input csv files still is not displayed. Can anyone point me how to deal with csv files with rather long pattern that must be displayed in resulted plot ? How can I make this happen ? Any idea ?
I have csv file which named with rather long character (just toy example here) :
TextTextTextTextTextTextTextTextTextTextTextTextTextText.csv
This is my resulted plot and desired plot that I want to achieve (here I showed multiple stack plot for only one csv file) :
I intend to continue the code part of my original plot. How can I get my desired plot ? Any way to tune size of face_wrap where rather long named file can be displayed in resulted plot ? Thanks a lot :)
Edit :
I want to adjust the space between multiple stack plot for each csv file as well. If multiple plot of two or three csv files are placed in one single page, How to dynamically adjust space, and plot size that make sure rather long named csv files are more readable. How can I achieve this ? Any idea please ?
New Edit :
Qualified <- list(
hotankarmaykuchakorla = data.frame( begin=seq(1, by=6, len=20), end=seq(4, by=6, len=20), pos.score=sample(30, 20)),
aksukexkerawataltay = data.frame( begin=seq(3, by=9, len=15), end=seq(6, by=9, len=15), pos.score=sample(28, 15))
)
UnQualified <- list(
hotankarmaykuchakorla = data.frame( begin=seq(9, by=12, len=30), end=seq(14, by=12, len=30), pos.score=sample(35, 30)),
aksukexkerawataltay = data.frame( begin=seq(13, by=10, len=20), end=seq(19, by=10, len=20), pos.score=sample(34, 20))
)
get multiple stack plot for this:
hotankarmaykuchakorla.validCandidate.Qualified.csv
hotankarmaykuchakorla.validCandidate.unQualified.csv
hotankarmaykuchakorla.invalidCandidate.Qualified.csv
hotankarmaykuchakorla.invalidCandidate.UnQualified.csv
Maybe using newline:
library(ggplot2)
# dummy data
df1 <- mtcars[, 1:3]
# make new long name
df1$cyl <- paste0("TextTextTextTextTextTextTextTextTextText", df1$cyl, ".csv")
# add newline
df1$cylWrap <-
paste0(substr(df1$cyl, 1, 20), "\n",
substr(df1$cyl, 21, nchar(df1$cyl)))
# plot
ggplot(df1, aes(mpg, disp)) +
geom_col() +
facet_wrap( ~cylWrap, scales = "free_x") +
theme(text = element_text(size = 14))
when I run the following code in R Studio, it works (produce the graph). But, when I knit the document to HTML it gives an error as: object "mydata" not found. How can I fix it?
mydata <- read.csv("impt5.csv")
get("mydata")
xyplot(gdppc ~ human + unemp +inv+indust | class, data = mydata,
auto.key = list(x = .85, y = .035, corner = c(0, 0)),
layout = c(4,1), main = "Per capita gdp by class")
set the working directory to the folder containing your CSV file.
You might want to create a R markdown file instead (.rmd), this is a easy to create an HTML document,or for any other format you want.
Please look into the R markdown help document.
Hope this helps.
More precisely, use:
mydata <- read.csv(paste0(getwd(),"impt5.csv"))
paste0() is the paste() function with sep=" "