GithubHelp home page GithubHelp logo

plotly / plotly.r Goto Github PK

View Code? Open in Web Editor NEW
2.5K 115.0 618.0 108.9 MB

An interactive graphing library for R

Home Page: https://plotly-r.com

License: Other

R 94.32% JavaScript 4.33% CSS 1.36%
r ggplot2 javascript data-visualization d3js shiny plotly webgl rstats r-package

plotly.r's Introduction

R-CMD-check CRAN Status CRAN Downloads monthly

An R package for creating interactive web graphics via the open source JavaScript graphing library plotly.js.

Installation

Install from CRAN:

install.packages("plotly")

Or install the latest development version (on GitHub) via {remotes}:

remotes::install_github("plotly/plotly")

Getting started

Web-based ggplot2 graphics

If you use ggplot2, ggplotly() converts your static plots to an interactive web-based version!

library(plotly)
g <- ggplot(faithful, aes(x = eruptions, y = waiting)) +
  stat_density_2d(aes(fill = ..level..), geom = "polygon") + 
  xlim(1, 6) + ylim(40, 100)
ggplotly(g)

https://i.imgur.com/G1rSArP.gifv

By default, ggplotly() tries to replicate the static ggplot2 version exactly (before any interaction occurs), but sometimes you need greater control over the interactive behavior. The ggplotly() function itself has some convenient “high-level” arguments, such as dynamicTicks, which tells plotly.js to dynamically recompute axes, when appropriate. The style() function also comes in handy for modifying the underlying trace attributes (e.g. hoveron) used to generate the plot:

gg <- ggplotly(g, dynamicTicks = "y")
style(gg, hoveron = "points", hoverinfo = "x+y+text", hoverlabel = list(bgcolor = "white"))

https://i.imgur.com/qRvLgea.gifv

Moreover, since ggplotly() returns a plotly object, you can apply essentially any function from the R package on that object. Some useful ones include layout() (for customizing the layout), add_traces() (and its higher-level add_*() siblings, for example add_polygons(), for adding new traces/data), subplot() (for combining multiple plotly objects), and plotly_json() (for inspecting the underlying JSON sent to plotly.js).

The ggplotly() function will also respect some “unofficial” ggplot2 aesthetics, namely text (for customizing the tooltip), frame (for creating animations), and ids (for ensuring sensible smooth transitions).

Using plotly without ggplot2

The plot_ly() function provides a more direct interface to plotly.js so you can leverage more specialized chart types (e.g., parallel coordinates or maps) or even some visualization that the ggplot2 API won’t ever support (e.g., surface, mesh, trisurf, etc).

plot_ly(z = ~volcano, type = "surface")

https://plot.ly/~brnvg/1134

Learn more

To learn more about special features that the plotly R package provides (e.g., client-side linking, shiny integration, editing and generating static images, custom events in JavaScript, and more), see https://plotly-r.com. You may already be familiar with existing plotly documentation (e.g., https://plotly.com/r/), which is essentially a language-agnostic how-to guide for learning plotly.js, whereas https://plotly-r.com is meant to be more wholistic tutorial written by and for the R user. The package itself ships with a number of demos (list them by running demo(package = "plotly")) and shiny/rmarkdown examples (list them by running plotly_example("shiny") or plotly_example("rmd")). Carson also keeps numerous slide decks with useful examples and concepts.

Contributing

Please read through our contributing guidelines. Included are directions for opening issues, asking questions, contributing changes to plotly, and our code of conduct.

plotly.r's People

Contributors

13bzhang avatar alanocallaghan avatar alyst avatar bersbersbers avatar chriddyp avatar cpsievert avatar dmurdoch avatar frankbornais avatar jackparmer avatar jameslamb avatar jcheng5 avatar karthik avatar mkcor avatar moutikabdessabour avatar msummersgill avatar msund avatar nielsenmarkus11 avatar pedrodz avatar pmur002 avatar rpkyle avatar salim-b avatar schloerke avatar sckott avatar talgalili avatar tdhock avatar timelyportfolio avatar trekonom avatar wfjvdham avatar wibeasley avatar zeehio 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  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

plotly.r's Issues

ggplotly export of tile geometry fails.

I don't know if I do something wrong or tiles are not yet supported by the exporter. When running

test <- data.frame(
  x = rep(c(1,3,6),2),
  y = rep(c(1,3), each = 3),
  w = rep(c(.5,2,1), 2),
  z = sample(rep(LETTERS[1:6])))

tilePlot <- ggplot(test, aes(x=x, y=y, fill = z)) + geom_tile(aes(width = w))
py$ggplotly(tilePlot);

I get the following Error:

Error in gg2list(gg) : No exportable traces
In addition: Warning message:
In layer2traces(L, df, misc) :
  Conversion not implemented for geom_tile (basic geom_tile), ignoring. Please open an issue with your example code at https://github.com/ropensci/plotly/issues

Problem with py$ggplotly

Hi! I've a ggplot that I want to send to plotly website. The ggplot appears in my screen without problems, but the py$ggplotly command sends an error. Here's a reproducible code with the error:

library(ggplot2)
library(plotly)

df = data.frame(error = c(0.0832544999, 0.0226680026, 0.0082536264, 
                          0.0049199958, 0.0003917755, 0.0003859976, 
                          0.0003888253, 0.0003953918, 0.0003958398), 
                sDev = c(8.188111e-03, 2.976161e-03, 1.466221e-03, 
                         2.141425e-03, 2.126976e-05, 2.139364e-05, 
                         2.169059e-05, 2.629895e-05, 2.745938e-05))

minimum <- 6
best.model <- 5
threshold <- df$error[minimum] + df$sDev[minimum]

# Plot of LOOCV
gplot <- ggplot(df, aes(x=1:length(error), y=error)) +
    scale_x_continuous(breaks = seq_along(df$error)) +
    geom_point(size = 3) +
    geom_line() +
    geom_errorbar(data = df, aes(x = 1:length(error), ymin = error - sDev, ymax = error + sDev), 
                  width = 0.1) + 
    geom_hline(data = data.frame(threshold = threshold), aes(yintercept = threshold, linetype = "Threshold", 
                                                             colour = "Threshold")) +
    geom_vline(data = data.frame(type = "Minimum CV error", col = "Minimum CV error", minimum = minimum), 
               aes(linetype = type, colour = col, xintercept = minimum), size = 1, show_guide = TRUE) +
    geom_vline(data = data.frame(type = "Best model", col = "Best model", best.model = best.model), 
               aes(linetype = type, colour = col, xintercept = best.model), size = 1, show_guide = TRUE) +
    scale_colour_manual(name = "Legend", values = c("Threshold" = "black", "Minimum CV error" = "red", "Best model" = "blue")) +
    scale_linetype_manual(name = "Legend", values = c("Threshold" = "dashed", "Minimum CV error" = "dotted", "Best model" = "dotted")) +
    theme_gray(base_size = 18) + 
    theme(axis.text = element_text(color = "black"), legend.key.height  = grid::unit(0.1, "npc")) +
    labs(x = "# of parameters", fontface = "bold") + 
    labs(y = "CV error") +
    labs(title = "Cross-validation error curve")

py <- plotly()
py$ggplotly(gplot)

Error in eval(expr, envir, enclos) : object 'error' not found

Any idea how to solve this issue? Any help is greatly appreciated.

Thanks!

Support functions from "scales" package

For example,

ggplot(iris, aes(x = Sepal.Length, y = Petal.Width/Petal.Length)) + geom_point() +
  scale_y_continuous(labels = percent_format())

does not work in plain "ggplot2" (you need to install and load "scales").

At the moment, ggplotly() does not convert (ignores) the labels = percent_format() part.

/cc @sckott

X-Axis Labels Issue When Creating Bar Charts

Refer to URL https://cyruslentin.shinyapps.io/kiei-proj/
Giving below code for ggplot2 & plotly via ggplot2 both using Shiny Apps

In the above URL, please refer to IIP > SpecifcMonth > Mode = QuickGraph //normal ggplot graph
Code

fileData <- read.csv("xsmFileData.csv") #csv file is attached herewith
par(mfrow=c(1,1), pin=c(6,4))
xsmDataPlot <- ggplot(dfrIipxData, aes(IndexName, CurrentMonth)) +
   geom_bar(stat="identity", width=0.8, fill=rainbow(length(dfrIipxData$IndexName))) +
   geom_text(aes(label=CurrentMonth), size=4, hjust=0.5, vjust=-0.1) +
   xlab("Index") + ylab("IIP Data") +
   theme(axis.text.x=element_text(angle=60, hjust=1, vjust=1))

Note
This works as required. Note that in this graph, the line "geom_text" is used.
Also note that in this graph the x-axis label are full text.

In the above URL, please refer to IIP > SpecifcMonth > Mode = Interactive //(plotly graph)
Code

fileData <- read.csv("xsmFileData.csv") #csv file is attached herewith ... same as above
par(mfrow=c(1,1), pin=c(6,4))
xsmIipxPlotly <- ggplot(fileData, aes(x=IndexName,y=CurrentMonth)) +
   geom_bar(stat="identity", width=0.8, fill=rainbow(length(dfrIipxData$IndexName))) +
   #geom_text(aes(label=CurrentMonth), size=4, hjust=0.5, vjust=-0.1) +
   xlab("Index") + ylab("IIP Data") +
   theme(axis.text.x=element_text(angle=60, hjust=1, vjust=1))
xsmIipx.py <- plotly("cyruslentin", "ji5rv9ag9k", "https://plot.ly")  # Open Plotly connection
xsmIipx.rs <- xsmIipx.py$ggplotly(xsmIipxPlotly, kwargs=list(filename=paste(thisInstance,"-xsmIipxPlotly",sep=""), fileopt="overwrite", auto_open=F))
tags$iframe(src=xsmIipx.rs$response$url, frameBorder="0", height=450, width=950)

Note
For plotly to generate the graph, the geom_text line(s) have to be commented. (I can live with this)
Further the x-axis labels are some numbers (corresponds to row-number). Why is this happening.

File "xsmFileData" can be found at https://github.com/cyruslentin/plotly.

Any help here would be appreciated

infer default hovermode based on plot data

we should analyze the plot data and if there are a lot of repeated x values across different traces, then choose hovermode="closest" (good for multiple time series).

otherwise we should default to hovermode="x" (good for scatter plots).

Time Series Graph Issue In Plotly

Refer to URL https://cyruslentin.shinyapps.io/kiei-proj/
Giving below code for ggplot2 & plotly via ggplot2 both using Shiny Apps

In the above URL, please refer to IIP > SpecificIndex > Mode = QuickGraph //normal ggplot graph
Code

fileData <- read.csv("xsiFileData.csv") #csv file is attached herewith
par(mfrow=c(1,1), pin=c(6,4))
xsiDataPlot <- ggplot(data=fileData, aes(x=FiscalMonth, y=CurrentMonth, label=CurrentMonth, group=1, color="ThisYear")) +
   geom_line(lwd=1.3) +
   geom_point(aes(y=CurrentMonth), size=2, color="black") +
   geom_line(mapping=aes(x=FiscalMonth, y=PreviousYear, label=PreviousMonth, group=1, color="PrevYear"),lwd=1.1) +
   geom_point(aes(y=PreviousYear), size=2, color="black") +
   xlab("Month") + ylab("IIP Data") +
   theme(axis.text.x=element_text(angle=80, hjust=1, vjust=1)) +
   theme(legend.title=element_blank())

Note
This works as required. Note that in this graph "geom_points" are used.

In the above URL, please refer to IIP > SpecificIndex > Mode = QuickGraph //normal ggplot graph
Code

fileData <- read.csv("xsiFileData.csv") #csv file is attached herewith ... same as above
par(mfrow=c(1,1), pin=c(6,4))
xsiDataPlot <- ggplot(data=fileData, aes(x=FiscalMonth, y=CurrentMonth, label=CurrentMonth, group=1, color="ThisYear")) +
   geom_line(lwd=1.3) +
   #geom_point(aes(y=CurrentMonth), size=2, color="black") +
   geom_line(mapping=aes(x=FiscalMonth, y=PreviousYear, label=PreviousMonth, group=1, color="PrevYear"),lwd=1.1) +
   #geom_point(aes(y=PreviousYear), size=2, color="black") +
   xlab("Month") + ylab("IIP Data") +
   theme(axis.text.x=element_text(angle=80, hjust=1, vjust=1)) +
   theme(legend.title=element_blank())

Note
For plotly to generate the graph, the geom_point line has to be commented.
The error message given is "undefined columns selected"
Even after commenting, the required graph in plotly is not proper.
Shows "null" in x-axis.

Query
Surely I am missing something ... is there something required to be done in plotly.
Is there a work around?

PS - how does one upload a csv file here?

Bad filename response with directories

When you set a directory within the filename like directory/file the API returns the directory two times. directorydirectory/file

When you use this as a simple example:

library(plotly)

py <- plotly(username="noqqe", key="MYKEY")

x <- rnorm(500)
data = list(x = x,
            type = 'histogramx')
l <- list(autosize = FALSE,
          width = 600,
          height = 400,
          showlegend = FALSE)

response <- py$plotly(data, kwargs = list(layout = l, filename="Mountainbike/TEST"))

filename <- response$filename
print(filename)

You recieve the following

$ Rscript lolo.R 
Loading required package: RCurl
Loading required package: methods
Loading required package: bitops
Loading required package: RJSONIO
Loading required package: ggplot2
[1] "MountainbikeMountainbike/TEST"

Support file naming/overwriting in ggplotly()

Just like the plotly() method lets you specify a filename and pass the overwrite option (via kwargs = list(filename = NULL, fileopt = NULL) line 115 of R/plotly.R), it would be fair for ggplotly() to offer this as well!

Error bars

Ggplot bar graphs and scatter plots that have error bars (i.e., those created with geom_errorbar) yield the following error:

Error in layer2traces(L, df, misc) : 
  conversion not implemented for geom_errorbar (basic geom_errorbar)

cached images in knitr

In this PR in the Python-API (plotly/plotly.py#183) I'm displaying and caching an image as the iframe loads. Our new embed code similarly displays an image as the iframe waits to load.

We should probably explore one of those two solutions for the kintr pubs

geom_points Issue In Plotly

Refer to URL https://cyruslentin.shinyapps.io/kiei-proj/

Giving below code for ggplot2 & plotly via ggplot2 both using Shiny Apps

In the above URL, please refer to IIP > FiscalYear > Mode = QuickGraph //normal ggplot graph
Code

fileData <- read.csv("xfyFileData.csv") #csv file is attached herewith
par(mfrow=c(1,1), pin=c(6,4))
xfyDataPlot <- ggplot(data=fileData, aes(x=ShortMonth, y=CurrentMonth, label=CurrentMonth,   group=FiscalYear, color=FiscalYear)) +
   geom_line(size=1.1) +
   geom_point(size=2, color="black") +
   xlab("Month") + ylab("IIP Data")

Note
This works as required. Note that in this graph "geom_points" are used.

In the above URL, please refer to IIP > FiscalYear > Mode = Interactive //(plotly graph)
Code

fileData <- read.csv("xfyFileData.csv") #csv file is attached herewith ... same as above
par(mfrow=c(1,1), pin=c(6,4))
xfyDataPlot <- ggplot(data=fileData, aes(x=ShortMonth, y=CurrentMonth, label=CurrentMonth, group=FiscalYear, color=FiscalYear)) +
   geom_line(size=1.1) +
   #geom_point(size=2, color="black") +
   xlab("Month") + ylab("IIP Data")
xfy.py <- plotly("username", "api-key", "https://plot.ly")  # Open Plotly connection
xfy.rs <- xfy.py$ggplotly(xfyDataPlot, kwargs=list(filename=paste(thisInstance,"-xfyDataPlot",sep=""), fileopt="overwrite", auto_open=F))
tags$iframe(src=xfy.rs$response$url, frameBorder="0", height=450, width=950)

Note
For plotly to generate the graph, the geom_point line has to be commented.
The error message given is "undefined columns selected"

PS - how does one attach a csv file here

conversion not implemented for geom_histogram

 data <- data.frame(x = rnorm(100))
 g <- ggplot(data, aes(x = x, y = ..density..)) + geom_histogram(binwidth = .5)
 r <- py$ggplotly(g)

gives the following error:

Error in gg2list(gg) : No exportable traces
In addition: Warning message:
In layer2traces(L, df, misc) :
Conversion not implemented for geom_histogram (basic geom_histogram), ignoring.
Please open an issue with your example code at https://github.com/ropensci/plotly/issues

theme colors/size

matching the colors and sizing for the ticks, labels, titles, and fonts

produce a text error message on plotly instead of an error in R

A quick thought. It'd be awesome to throw in graphs when you can get part of the way there. Let me know if I'm way off or missing something here.

For example, on this plot:

d <- data.frame(x=c(1, 2, 2, 3, 4, 4), y=c(1, 1, 2, 2, 2, 3),
t=c('a', 'a', 'a', 'b', 'b', 'b'), r=c(1, 2, 3, 4, 5, 6))
p <- ggplot() +
geom_polygon(data=d, mapping=aes(x=x, y=y, group=t)) +
geom_point(data=d, aes(x=x, y=y, colour=t)) +
labs(title="geom_polygon")

We get decently close: https://plot.ly/~RgraphingAPI/1372/geompolygon/.

If I run it, I get "conversion not implemented for geom_text (basic geom_text)". When I take out that line, it draws the graph.

My thought was that it'd be awesome to draw it on the first go-around, and if we can't get it all in, cover what we can and message the user something along the lines of "We don't support x yet, so relevant parts of your graph won't be drawn." Then, we can take a shot at it.

plotly package installation

i want to install plotly package in R, from github

library(devtools)
install_github("ropensci/plotly")
and i have an error message:

Downloading github repo ropensci/plotly@master
Error in function (type, msg, asError = TRUE) : couldn't connect to host
i have searched on the internet and i found that it's a problem of proxy, i tried:

set_config(
use_proxy(url="https://github.com/ropensci/plotly", port=8080, username="_",password="_")
)
but still have the same problem, i don't know what to put in url and port values, i have two accounts on Githup and plotly

thank you for your help

Conversion not implemented for geom_vline

Also, plotly rendering of geom_point gives an error msg: Error in [.data.frame(df, 1, invariable.names) :
undefined columns selected

Code (apologies for not making this shorter but it's quite simple):
suppressPackageStartupMessages(require(shiny))
suppressPackageStartupMessages(require(ggplot2))
suppressPackageStartupMessages(require(doBy))
suppressPackageStartupMessages(require(plotly))

## from mydsutils.R
myformat_number <- function(x) {
    if (class(x) != "num") x <- as.numeric(x)
    return(format(x, big.mark=',')) # 000's separator
}

mymedian <- function(vector) {
    if (is.factor(vector)) 
        return(factor(levels(vector)[median(as.numeric(vector))], levels(vector)))
    else return(median(vector))
}

## App specific stuff
diamonds_df <- diamonds
features_lst <- names(diamonds_df)
features_lst <- features_lst[features_lst != "price"]

# Compute medians for all features which will be used to display as the default "test" diamond
median_diamonds_df <- summaryBy(. ~ factor(0), data=diamonds_df, FUN=median, 
                                keep.names=TRUE)
# summaryBy does not compute stats for factor variables
median_diamonds_df$cut <- mymedian(diamonds_df[, "cut"])
median_diamonds_df$color <- mymedian(diamonds_df[, "color"])
median_diamonds_df$clarity <- mymedian(diamonds_df[, "clarity"])

# Run regression
prediction_mdl <- lm(reformulate(features_lst, response="price"), 
                     data = diamonds_df)
#print(summary(prediction_mdl))

## Create test set & get predictions on the test set
predict_price <- function(df) {
    prediction <- predict(prediction_mdl, df, interval="confidence")
    df$price.predict.fit <- prediction[, "fit"]
    df$price.predict.lwr <- prediction[, "lwr"]
    df$price.predict.upr <- prediction[, "upr"]
    return(df)
}
test_diamonds_df <- predict_price(median_diamonds_df)
#print(test_diamonds_df)

## Gather inputs from Web UI
input <- list("plot.sampleSize"=5000, "predict.carat"=0.7, "predict.cut"="Premium",
              "plot.x"="carat", "plot.color"="color", "plot.facet_row"=".", 
              "plot.facet_col"=".", "plot.jitter"=0, "plot.smooth"=0)

diamonds_smp_df <- diamonds_df[sample(nrow(diamonds_df), input$plot.sampleSize), ]
test_diamonds_df$carat <- input$predict.carat
test_diamonds_df$cut <- factor(input$predict.cut, levels=levels(median_diamonds_df$cut))
test_diamonds_df <- predict_price(test_diamonds_df) 

## Display plot
py <- plotly()

create_ggplot <- function(input) {
    ui_x_name <- input$plot.x
    ui_x_val <- test_diamonds_df[ ,ui_x_name]
    if (!is.factor(median_diamonds_df[, ui_x_name]))
        ui_x_median <- median_diamonds_df[, ui_x_name]
    else
        ui_x_median <- unclass(median_diamonds_df[, ui_x_name])[1]

    p <- ggplot(diamonds_smp_df, aes_string(x=ui_x_name, y="price"))

    if (input$plot.color != 'None')
        p <- p + geom_point() + aes_string(color=input$plot.color)
    else
        p <- p + geom_point(color="grey")

    facets <- paste(input$plot.facet_row, '~', input$plot.facet_col)
    if (facets != '. ~ .')
        p <- p + facet_grid(facets)

    if (input$plot.jitter)
        p <- p + geom_jitter()
    if (input$plot.smooth)
        p <- p + geom_smooth()

    # Format y-axis
    p <- p + ylab("price ($)")
    p <- p + scale_y_continuous(labels=myformat_number)

    # Display median (default for unspecified features) of X-axis feature
    aes_str <- paste0("linetype=\"dotted\", xintercept=as.numeric(", ui_x_name, ")")
    aes_mapping <- eval(parse(text = paste("aes(", aes_str, ")")))            
    p <- p + geom_vline(mapping=aes_mapping, 
                        data=median_diamonds_df, show_guide=TRUE)
    p <- p + scale_linetype_identity(guide="legend", name="Stats", labels="median")

    # Plot the prediction point & conf. interval
    aes_str <- paste0("y=price.predict.fit, x=", ui_x_name)
    aes_mapping <- eval(parse(text = paste("aes(", aes_str, ")")))
    p <- p + geom_point(aes_mapping,
                        data=test_diamonds_df,
                        color="red", pch=7, size=5)

    aes_str <- paste0(
        "ymax=price.predict.upr, ymin=price.predict.lwr, x=", ui_x_name)
    aes_mapping <- eval(parse(text = paste("aes(", aes_str, ")")))            
    p <- p + geom_errorbar(aes_mapping,
                           data=test_diamonds_df,    
                           color="red", width=0.1)

    # Plot the regression line
    p <- p + geom_smooth(method="lm")

    # linetype legend messes up the fill legend
    p <- p + guides(color=guide_legend(override.aes=list(linetype=0)))

    return(p)
}    

input$plot.x <- "carat"
gp_carat <- create_ggplot(input)
print(gp_carat)
pyout_carat <- py$ggplotly(gp_carat)
pyout_carat$response$url

Error in browseURL(resp$url) : 'url' must be a non-empty character string

Good time of the day,
Anytime I'm trying to send my ggplots to plotly i get this error -
Error in browseURL(resp$url) : 'url' must be a non-empty character string
Garphs are quite complex and code looks like that.
Gr_water = ggplot() +
geom_line(data = Daily_A_114, aes(x=Doy, y=ma(SWC_1_100)),position=pd,linetype=2) +
geom_point(data = Daily_A_114, aes(x=Doy, y=(SWC_1_100)),position=pd,size=2, shape=21, fill="white",alpha=.3)+
geom_rect(data = Daily_A_114, aes(x=Doy,xmin=Doy-1,xmax=Doy+1, y=Rain_mm_Tot_sums, ymin=0, xmin=3), position=pd, size=1,alpha=.4) +
geom_rect(data = Daily_O_114, aes(x=Doy,xmin=Doy-1,xmax=Doy+1, y=P_Tot_sums, ymin=0, xmin=3), position=pd, size=1,alpha=1) +
geom_line(data = Daily_O_114, aes(x=Doy, y=ma(SWC_1_100)),position=pd) +
geom_point(data = Daily_O_114, aes(x=Doy, y=(SWC_1_100)),position=pd,size=2, shape=21, fill="black",alpha=.3)+
coord_cartesian(xlim = c(110, 365),ylim = c(0, 45))+
scale_x_continuous(breaks = round(seq(120, 360, by = 30),1))+
xlab("Day of the year") +
ylab(expression(bold(paste("SWC at 5cm depth (%)"," ",sep="")))) +
theme(axis.title.y = element_text(size = 13, face="bold")) +
theme(plot.margin = unit(c(0,1,0,2), "lines"))+
theme(axis.title.x = element_text(size =15, face="bold"))

py <- plotly(username=username, key=key)
plot_list = gg2list(Gr_water)

Unable to generate a heat map plot generated by cummeRbund

Hi,

I am using the following commands:

library(cummeRbund)
library(plotly)
cuff_data <- readCufflinks('CLL-all-cuffdiff_out')
mySigGeneIds<-getSig(cuff_data,alpha=0.02,level='genes')
mySigGenes<-getGenes(cuff_data,mySigGeneIds)
py <- plotly()
myHeatmap<-csHeatmap(mySigGenes,cluster='row')
myHeatmap
r <- py$ggplotly(myHeatmap)
Error in gg2list(gg) : No exportable traces
In addition: Warning message:
In layer2traces(L, df, misc, trace.list$plot) :
Conversion not implemented for geom_rect (basic geom_rect), ignoring. Please open an issue with your example code at https://github.com/ropensci/plotly/issues
screen shot 2014-07-31 at 11 17 17 am

Issues with plotly and ggthemes fivethirtyeight()

When I use the fivethirtyeight() theme from the ggthemes package, I get the following error:
Error in eval(expr, envir, enclos) : object 'size' not found

This error disappears once I take off the fivethirtyeight() theme. Any ideas why this might be?

Remove axis lines and show legend size for scatter

It would be sweet to remove the axis lines by default. I do that manually now after drawing the plot, but it'd be sweet to remove them by default.

It would also be cool to match the size of the markers and the legend size of the marker. It appears that the legend size defaults to 2 (maybe I'm wrong?) for a scatter series. To change, it, I go to traces > style > marker > and change it to eight, which changes it in the legend. It'd be cool to match the size on the plot and legend right out of the gate.

Ggplotly is most excellent. Thanks!

plotly

Submit package to CRAN

It would be great to get this package to CRAN at some point soon.

  • Deal with the license issue. MIT + License file is now required by the CRAN maintainers.
  • Write unit tests with testthat
  • Write documentation with roxygen2
  • Change URL and bugreports URL in the DESCRIPTION file.
  • Add Travis integration and shield to README
  • Write a vignette
  • Write a blogpost for rOpenSci

Minor nuisances:

  • Remove .Rhistory files from repo.

expose RCurl options to user

some folks use the package behind proxies, and need to configure their own RCurl parameters. There should be a way to expose the user a parameter so that she can provide her own RCurl handle.

using color as an additional variable in ggplot2

I am trying to plot an additional variable using colour:

p = ggplot(mds, aes(x = coord.1, y = coord.2, label = City, colour = Division)) + geom_text()

This works fine in Rstudio and produces:
screen shot 2014-11-12 at 9 34 34 am

FYI, the head of my data looks like this

head(mds)
State City coord.1 coord.2 X2013.rank Division
1 Alabama HUNTSVILLE 1.561284 0.2228790 126 East South Central
2 Alabama MOBILE 6.088862 0.8343259 122 East South Central
3 Alabama BIRMINGHAM 9.978292 -3.6507234 101 East South Central
4 Alabama MONTGOMERY 15.454877 -4.8520206 111 East South Central
5 Arizona TUCSON 23.225289 -0.4438650 33 Mountain
6 Arizona PEORIA -7.283954 9.1252792 149 Mountain

Thanks!!

Double interactive data entry and legend settings

hi all,

I am not sure if this is a bug or just my part of doing: I am converting a basic line graph with multiple lines - a data frame column named "stripe" is mapped to both "shape" and "color". The R output looks like:

screen shot 2014-05-21 at 9 53 38 pm

but the py$gplotly() output looks like:
https://plot.ly/~fwang2/8/mpi-io-wide-stripe-read-scaling/

There are two major issues:

  1. Legends are messed up
  2. Move mouse to data point, it shows double entries.

Did I miss something here?

TIA,

Feiyi

Organising your output

Hey plotly gang, I've just been trying out your product using the R API. It seems pretty useful. This isn't an issue as such, I was just looking for some help.

I've seen once you have produced your graph you can go to your workspace rename it to something more useful and pop it in a folder. Is there any way of doing this via your code in R? Otherwise i could see my workspace becoming a real mess very quickly.

I found something in the user guide i thought might help but it wouldn't run. Maybe i'm using it incorrectly or perhaps it doesn't do what i thought it would do at all. Any help would be appreciated.

#initialize acccess to the API
py <- plotly()
#create plot
box<-ggplot(iris, aes(factor(Species), Petal.Width)) + geom_boxplot()
#push your plot through the API
p2 <- py$ggplotly(box)
#how do you name and organise stuff? does this do it
p3 <- py$plotly(box, kwargs=list(filename="boxlabeltest", fileopt="overwrite"))

Error in toJSON(unclass(x), container, collapse, ..., .level = .level +  : 
  error in evaluating the argument 'x' in selecting a method for function 'toJSON': Error in unclass(x) : cannot unclass an environment

Master list of supported/unsupported features

Hi all --

This great post is keeping track of the unsupported ggplot geoms: http://aarongonzales.net/plotly_examples.html.

I thought I'd copy that master list over here, just to make y'all aware. Feel free to re-organize the issue (close it, break it out into separate issues, etc!) in anyway that you'd like!

geoms

  • geom_abline
  • geom_area
  • geom_bar
  • geom_bin2d
  • geom_boxplot
  • geom_contour
  • geom_crossbar
  • geom_density
  • geom_density2d
  • geom_dotplot
  • geom_errorbar
  • geom_errorbarh
  • geom_freqpoly
  • geom_hex() (untested)
  • geom_histogram
  • geom_hline
  • geom_jitter
  • geom_line()
  • geom_linerange
  • geom_map
  • geom_path()
  • geom_point()
  • geom_pointrange
  • geom_polygon()
  • geom_quantile
  • geom_raster
  • geom_rect
  • geom_ribbon
  • geom_rug
  • geom_segment()
  • geom_smooth
  • geom_step
  • geom_text
  • geom_tile
  • geom_violin
  • geom_vline

stats

  • stat_abline
  • stat_bin
  • stat_bin2d
  • stat_bindot
  • stat_bindot
  • stat_binhex
  • stat_contour
  • stat_density
  • stat_density2d
  • stat_ecdf
  • stat_function
  • stat_hline
  • stat_identity
  • stat_qq
  • stat_quantile
  • stat_smooth
  • stat_spoke
  • stat_sum
  • stat_summary
  • stat_summary_hex
  • stat_summary2d
  • stat_unique
  • stat_vline
  • stat_ydensity

other ggplot stuff

  • expand_limits
  • guide_legend
  • guide_colourbar(guide_colorbar)
  • scale_alpha(scale_alpha_continuous, scale_alpha_discrete)
  • scale_area()
  • scale_color_brewer
  • scale_color_continuous
  • scale_color_discrete
  • scale_color_gradient
  • scale_color_gradient2
  • scale_color_gradientn
  • coord_cartesian
  • coord_equal
  • coord_fixed
  • coord_flip
  • coord_map
  • coord_polar
  • coord_trans
  • facet_grid
  • facet_null
  • facet_wrap
  • position_dodge
  • position_fill
  • position_identity
  • position_jitter
  • position_stack

Encoding problems using ggplot2, Shiny and Plotly

Hi,
I'm trying to create an app for a website using R, ggplot2, Shiny and Plotly, and I'm facing two different problems. I would really appreciate any help or advice.

  1. As I live in Spain I have to deal with a number of special symbols (eg:Á, á, à, é, É, ñ, ï, etc). I've solved the issue on the shiny part of the app, but I still have problems with titles on the plotly plots.
  2. The aes parameters (axes ticks, labels, fonts) on plotly plots are not responding to those on the code (using ggplot2).

The expected look of the plotly plots it's available by downloading them as png files.

Here the reproducible code (pick Agrón as Municipality)

Server file

library(shiny)
library(plotly)
library(ggplot2)
library(scales)

load(url('http://gedemced.uab.cat/images/ANDALUCIA.Rdata'))

# Define a server for the Shiny app

shinyServer(function(input, output) {  
  output$ComposicionPlot <-renderUI({ 
    Mun <- ANDALUCIA[ANDALUCIA$MUN2 %in% input$MUN2, ]
    comp<- ggplot(data=Mun, aes(x=YEAR, y=POP, fill=ORIGIN)) + 
            geom_bar(stat="identity", colour="black")+
            scale_x_continuous(breaks=seq(2000,2013, 2))+
            ggtitle(paste("Population composition",input$MUN2, sep=": "))+
            scale_fill_discrete(breaks=c("Spanish-born", "Foreign-born"),
                                labels=c("Spanish-born", "Foreign-born"))+
            theme(plot.title = element_text(lineheight=5.6, size=15, face="bold"),
                  legend.title = element_blank(),
                  legend.text = element_text(colour="black", size = 10),
                  legend.position="bottom",
                  legend.background = element_rect(fill="#FFFFFF"),
                  axis.title.x = element_blank(),
                  axis.text.x  = element_text(angle = 0,vjust=0.5, size=10,colour="black",face="bold"),
                  axis.title.y = element_text(face="bold", colour="black", size=10),
                  axis.text.y  = element_text( vjust=0.5, size=10,colour="black",face="bold"),
                  plot.background = element_rect(fill = "#FFFFFF"))+
            ylab("Population")


    py <- plotly(username="Username", key="whatever")  # Open Plotly connection

    res <- py$ggplotly(comp, kwargs=list(filename="Prueba", 
                                           fileopt="overwrite", # Overwrite plot in Plotly's website
                                           auto_open=FALSE))

    tags$iframe(src=res$response$url,
                frameBorder="0",  # Some aesthetics
                height=400,
                width=650)

  })
  output$ComposicionPlot2 <-renderUI({ 
    Mun <- ANDALUCIA[ANDALUCIA$MUN2 %in% input$MUN2, ]
    comp<- ggplot(data=Mun, aes(x=YEAR, y=PROP, fill=ORIGIN)) + 
      geom_bar(stat="identity", colour="black")+
      scale_x_continuous(breaks=seq(2000,2013, 2))+
      scale_y_continuous(labels = percent)+
      ggtitle(paste("Population composition",input$MUN2, sep=": "))+
      scale_fill_discrete(breaks=c("Spanish-born", "Foreign-born"),
                          labels=c("Spanish-born", "Foreign-born"))+
      theme(plot.title = element_text(lineheight=5.6, size=15, face="bold"),
            legend.title = element_blank(),
            legend.text = element_text(colour="black", size = 10),
            legend.position="bottom",
            legend.background = element_rect(fill="#FFFFFF"),
            axis.title.x = element_blank(),
            axis.text.x  = element_text(angle = 0,vjust=0.5, size=10,colour="black",face="bold"),
            axis.title.y = element_text(face="bold", colour="black", size=10),
            axis.text.y  = element_text( vjust=0.5, size=10,colour="black",face="bold"),
            plot.background = element_rect(fill = "#FFFFFF"))+
      ylab("Percentage")


    py <- plotly(username="Username", key="whatever")  # Open Plotly connection

    res <- py$ggplotly(comp, kwargs=list(filename="Prueba2", 
                                         fileopt="overwrite", # Overwrite plot in Plotly's website
                                         auto_open=FALSE))

    tags$iframe(src=res$response$url,
                frameBorder="0",  # Some aesthetics
                height=400,
                width=650)

  })
  output$downloadPlot <- downloadHandler(
    filename = function() { paste(input$MUN2, '.png', sep='') },
    content = function(file) {
      png(file,width = 600, height = 400)
      Mun <- ANDALUCIA[ANDALUCIA$MUN2 %in% input$MUN2, ]
      print(ggplot(data=Mun, aes(x=YEAR, y=POP, fill=ORIGIN)) + geom_bar(stat="identity", colour="black")+
              scale_x_continuous(breaks=seq(2000,2013, 1))+
              ggtitle(paste("Population composition",input$MUN2, sep=": "))+
              scale_fill_discrete(breaks=c("Spanish-born", "Foreign-born"),
                                  labels=c("Spanish-born", "Foreign-born"))+
              theme(plot.title = element_text(lineheight=5.6, size=20, face="bold"),
                    legend.title = element_blank(),
                    legend.text = element_text(colour="black", size = 20),
                    legend.position="bottom",
                    legend.background = element_rect(fill="#FFFFFF"),
                    axis.title.x = element_blank(),
                    axis.text.x  = element_text(angle = 90,vjust=0.5, size=20,colour="black",face="bold"),
                    axis.title.y = element_text(face="bold", colour="black", size=20),
                    axis.text.y  = element_text( vjust=0.5, size=20,colour="black",face="bold"),
                    plot.background = element_rect(fill = "#FFFFFF"))+
              ylab("Population"))
      dev.off()
    })
  output$downloadPlot2 <- downloadHandler(
    filename = function() { paste(input$MUN2, '.png', sep='') },
    content = function(file) {
      png(file,width = 600, height = 400)
      Mun <- ANDALUCIA[ANDALUCIA$MUN2 %in% input$MUN2, ]
      print(ggplot(data=Mun, aes(x=YEAR, y=PROP, fill=ORIGIN)) + geom_bar(stat="identity", colour="black")+
              scale_x_continuous(breaks=seq(2000,2013, 1))+
              scale_y_continuous(labels = percent)+
              ggtitle(paste("Population composition",input$MUN2, sep=": "))+
              scale_fill_discrete(breaks=c("Spanish-born", "Foreign-born"),
                                  labels=c("Spanish-born", "Foreign-born"))+
              theme(plot.title = element_text(lineheight=5.6, size=20, face="bold"),
                    legend.title = element_blank(),
                    legend.text = element_text(colour="black", size = 20),
                    legend.position="bottom",
                    legend.background = element_rect(fill="#FFFFFF"),
                    axis.title.x = element_blank(),
                    axis.text.x  = element_text(angle = 90,vjust=0.5, size=20,colour="black",face="bold"),
                    axis.title.y = element_text(face="bold", colour="black", size=20),
                    axis.text.y  = element_text( vjust=0.5, size=20,colour="black",face="bold"),
                    plot.background = element_rect(fill = "#FFFFFF"))+
              ylab("Percentage"))
      dev.off()
    })
  output$downloadData <- downloadHandler(

    # This function returns a string which tells the client
    # browser what name to use when saving the file.
    filename = function() {
      paste(input$MUN2, input$filetype, sep = ".")
    },

    # This function should write data to a file given to it by
    # the argument 'file'.
    content = function(file) {
      sep <- switch(input$filetype, "csv" = ",", "txt" = "\t")

      # Write to a file specified by the 'file' argument
      write.table(ANDALUCIA[ANDALUCIA$MUN2 %in% input$MUN2, ], file, sep = sep,
                  row.names = FALSE)
    }
  )
})

ui file

load(url('http://gedemced.uab.cat/images/ANDALUCIA.Rdata'))
# Define the overall UI
shinyUI(fluidPage(
  titlePanel("Autonomous Community: ANDALUSIA"),

  sidebarPanel(
    selectInput("MUN2", "Municipality", 
                choices=unique(ANDALUCIA$MUN2)),

    downloadButton('downloadPlot', 'Download plot 1'),
    downloadButton('downloadPlot2', 'Download plot 2'),
    radioButtons("filetype", "File extension:",
                 choices = c("csv", "txt")),
    downloadButton('downloadData', 'Download data'),
    # HTML info
    div(style = "margin-top: 10px; margin-left: 0px; width: 200px; ", HTML("Elaboration:")),
    div(style = "margin-top: 1px;margin-left: 0px; ", HTML("<a href='http://gedemced.uab.cat/'><img style='width: 150px;' src='http://gedemced.uab.cat/images/logo-GEDEM-01peque.png'/>")),
    div(style = "margin-top: 5px;", HTML("Data: <a href='http://www.ine.es/'>INE - Instituto Nacional de Estadí­­stica</a>"))

  ),    
  mainPanel( 
    htmlOutput("ComposicionPlot"),
    htmlOutput("ComposicionPlot2")
  )
  ))

does plotly respect the timezone?

I just got this email:

Hi there Toby,

How are you? I've just stumbled across the greatness of Plotly and in particular, your ggplotly code (really cool!).

I've managed to plot a ggplot time series, but I've noticed that the timezone of the time series seems to have changed…

Is there a way to either 1) tell ggplotly what timezone to use, or 2) tell ggplotly not to convert the timezone?

Thanks in advance for you response.

Cheers,
Matt.

Dr Matthew J Burns
email: [email protected]

Missing legend title

Following up on #153 ...
When you convert

xfyDataPlot <- ggplot(data=fileData, aes(x=ShortMonth, y=CurrentMonth,
                                         label=CurrentMonth,
                                         group=FiscalYear)) +
  geom_line(aes(color=FiscalYear), size=1.1) +
  geom_point(size=2, color="black") +
  xlab("Month") + ylab("IIP Data")

with ggplotly(), the legend title is missing--it's there if the geom_point trace is commented out...

Possibly relevant for #36 too.

zoom on this map

I'm not sure if I'm missing something here, but the zoom on this one is a bit weird, and it doesn't seem like there is more data we're fitting for:

https://plot.ly/~RgraphingAPI/948/

So if I make the graph, it looks like the "map" screenshot, but then if I zoom it a bit, it looks like the "zoom" shot. Hypothesis: because it's being drawn from ggplot, maybe there is something coming through as part of the scale? Or is it attaching to zero?

This is fun stuff. I'll talk to Alex about it. It'd also be sweet to auto-size them to something like 800 x 550 or so if we could.

Some numerical JSON fields are cast as strings

In this plot: https://plot.ly/~RgraphingAPI/554/sepallength-vs-petalwidth/, the json looks something like:

{
   "x": [...],
   "y": [...],
   "marker": {"size": "1"}
}

the marker.size attribute should be a number and not a string, e.g.

{
   "x": [...],
   "y": [...],
   "marker": {"size": 1}
}

In this case, plotly didn't understand the string types in marker.size, plotly implicitly set the size to 6. Once it's a number, a marker size and the legend size will look consistent in plotly.

Error in function (type, msg, asError = TRUE)

When I try to convert my ggplot2 graphic in R to plotly, it gives the following error message. What does it mean?

"Error in function (type, msg, asError = TRUE) :
error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure"

Here is the full code:
library(ggplot2)
flowers<-ggplot(iris, aes(x=Sepal.Length, y=Petal.Length)) + geom_point(col="blue")
library(plotly)

set_credentials_file("MyUsername", "Mykey") ## i left out my logins
py <- plotly()
r<-py$ggplotly(flowers)
r$response$url

Bug in signup function

signup("muschellij2", "[email protected]")
Error in signup("muschellij2", "[email protected]") :
object 'key' not found

Code:
function (username = NULL, email = NULL)
{
if (is.null(username))
key <- getOption("plotlyUsername", stop("you need a user name for Plot.ly - See the signup function"))
if (is.null(key))
key <- getOption("plotlyKey", stop("you need an API key for Plot.ly - See the signup function"))

key is not set - nor can you set it.

cant use ggplotly

Hi I have been trying to get the ggplotly function to work with plotly. I have tried some of my own ggplot functions as well as the example given by the developers. Every time I get "Error: attempt to apply non-function"

Proposed re-design

With the configuration files we can re-architect the module to be a little more "R"-y. I propose the following interface:

Before

py = plotly(username, key)
trace0 = list(x=...y=...)
py$plotly(trace0)

After

plotly:::set_credentials(username, key)
plotly:::plot(trace0)

Or, if you prefer to send your credentials on a per-call basis (e.g. you're using the R demo account):

plotly:::plot(trace0, username=..., key=....)

And similarly for the other functions:

plotly:::ggplotly(..., plotly_options)
plotly:::plot(..., plotly_options)
plotly:::export_image(..., plotly_options)
plotly:::get_figure(..., plotly_options)

With additional functionality ...

figure = plotly:::get_figure(file_owner, file_id, plotly_options) # returns a list of lists of lists of ... (plotly's JSON graph JSON)

data = plotly:::get_data(figure) # doesn't make a request to plotly, it just removes strips keys out of the named list

A few questions I have (because I'm not an R expert)

1 - Is it the R convention to have nested modules/functions?

e.g. in Python we do:

import plotly.plotly as py

# all the functions in py, call the plotly servers
py.plot(...)
py.iplot(...)
py.get_figure(...)
py.image.save_as(...)

# other functions, like tools, are in a separate namespace:

```python
import plotly.tools as tls
tls.embed(figure)

Do we do a similar thing in R? Or do we keep all the functions at the same "level", e.g.

This:

plotly:::embed(figure)

or this:

plotly:::tools:::embed(figure) #??

factors converted to numeric

Love this package!

In the following plot I experience factors being changed to numeric:

library(ggplot2)
library(plotly)

dat <- structure(list(person = structure(c(4L, 1L, 5L, 4L, 1L, 3L, 1L, 
    4L, 3L, 2L, 1L), .Label = c("greg", "researcher", "sally", "sam", 
    "teacher"), class = "factor"), state = structure(c(1L, 6L, 10L, 
    11L, 4L, 2L, 8L, 5L, 9L, 7L, 3L), .Label = c("Computer is fun. Not too fun.", 
    "How can we be certain?", "I'm hungry.  Let's eat.  You already?", 
    "I am telling the truth!", "I distrust you.", "No it's not, it's dumb.", 
    "Shall we move on?  Good then.", "There is no way.", "What are you talking about?", 
    "What should we do?", "You liar, it stinks!"), class = "factor"), 
        n = c(6, 5, 4, 4, 5, 5, 4, 3, 5, 6, 6), start = c(0, 6, 11, 
        15, 19, 24, 29, 33, 36, 41, 47), end = c(6, 11, 15, 19, 24, 
        29, 33, 36, 41, 47, 53)), .Names = c("person", "state", "n", 
    "start", "end"), row.names = c("1", "2", "3", "4", "5", "6", 
    "7", "8", "9", "10", "11"), class = c("colsplit2df", "data.frame"
    ))

m <- ggplot(dat, aes(colour=state)) + 
    geom_segment(aes(x=start, xend=end, y=person, yend=person), size=3) +
    xlab("Duration") + theme(legend.position="none")

tr$ggplotly(m)

Here is the plot: https://plot.ly/~tyler.rinker/9/

unsupported features from the r cookbook

Here are some remaining unsupported features as taken from the great ggplot2 cookbook.

The cookbook examples are in this branch: https://github.com/ropensci/plotly/tree/add-r-cookbook-tests, in this folder: https://github.com/ropensci/plotly/tree/add-r-cookbook-tests/tests/cookbook-test-suite

ggplot dendrogram cannot be added to plotly

Hi, I am not able to transform a specific ggplot2 in R to plotly using the api. After having installed and run library(plotly) without any issues I ran the following code in Rstudio server:

hc<-hclust(dist(mtcars),method="ward.D2")
k <- 3
dendr <- dendro_data(hc,type="rectangle")
clust<- cutree(hc,k=k)
clust.df <- data.frame(label=names(clust), cluster=factor(clust))
# dendr[["labels"]] has the labels, merge with clust.df based on label column
dendr[["labels"]] <- merge(dendr[["labels"]],clust.df, by="label")
rect <- aggregate(x~cluster,label(dendr),range)
rect <- data.frame(rect$cluster,rect$x)
ymax <- mean(hc$height[length(hc$height)-((k-2):(k-1))])
# plot the dendrogram; note use of color=cluster in geom_text(...)
ggdendtest<- ggplot() + 
geom_segment(data=segment(dendr), aes(x=x, y=y, xend=xend, yend=yend)) + 
geom_text(data=label(dendr), aes(x, y, label=label, hjust=-0.1,
                                   color=cluster), size=4) +
geom_rect(data=rect, aes(xmin=X1-.3, xmax=X2+.3, ymin=0, ymax=ymax), 
            color="red", fill=NA)+
coord_flip() + scale_y_reverse(expand=c(0.2, 0)) + 
ylab("Distance") +
theme(axis.line.y=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.y=element_blank(),
        axis.title.y=element_blank(),
        panel.background=element_rect(fill="white"),
        panel.grid=element_blank(),
        legend.title=element_blank())


ggpy<-plotly()
ggpy.r<-ggpy$ggplotly(ggdendtest)
ggpy.r$response$url

This results in the following errors:

Error in eval(expr, envir, enclos) : object 'size' not found
In addition: Warning messages:
1: In layer2traces(L, df, misc, trace.list$plot) :
  Conversion not implemented for geom_text (basic geom_text), ignoring. Please open     an issue with your example code at https://github.com/ropensci/plotly/issues
2: In layer2traces(L, df, misc, trace.list$plot) :
  Conversion not implemented for geom_rect (basic geom_rect), ignoring. Please open an issue with your example code at https://github.com/ropensci/plotly/issues

Following the suggestion I opened an issue, hoping anyone can help me out.

Further info

The output of my sessionInfo() is:

 R version 3.1.0 (2014-04-10)
 Platform: x86_64-pc-linux-gnu (64-bit)

 locale:
 [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C         LC_TIME=C            LC_COLLATE=C         LC_MONETARY=C       
 [6] LC_MESSAGES=C        LC_PAPER=C           LC_NAME=C            LC_ADDRESS=C         LC_TELEPHONE=C      
 [11] LC_MEASUREMENT=C     LC_IDENTIFICATION=C 

 attached base packages:
  [1] stats     graphics  grDevices utils     datasets  methods   base     

 other attached packages:
  [1] ggdendro_0.1-14       cluster_1.15.2        plotly_0.4            RJSONIO_1.2-0.2       RCurl_1.95-4.1       
 [6] bitops_1.0-6          devtools_1.5          extrafont_0.16        RColorBrewer_1.0-5    scales_0.2.4         
 [11] vegan_2.0-10          lattice_0.20-29       permute_0.8-3         splitstackshape_1.2.0 data.table_1.9.2     
 [16] BurStMisc_1.00        reshape2_1.4          xlsx_0.5.5            xlsxjars_0.6.0        rJava_0.9-6          
 [21] ggplot2_0.9.3.1       plyr_1.8.1           

 loaded via a namespace (and not attached):
 [1] MASS_7.3-32      Rcpp_0.11.1      Rttf2pt1_1.3     colorspace_1.2-4 digest_0.6.4     evaluate_0.5.5   extrafontdb_1.0 
 [8] formatR_0.10     grid_3.1.0       gtable_0.1.2     httr_0.3         knitr_1.6        labeling_0.2     memoise_0.2.1   
[15] munsell_0.4.2    parallel_3.1.0   proto_0.3-10     stringr_0.6.2    tools_3.1.0      whisker_0.3-2  

I am running R and Rstudio server (v. 0.98.501) on an Ubuntu 12.04 server LTS system.

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.