Convert ggplot graph to plotly

ggplot2

#1

Hello I have created a shiny app which creates the ggplot below but when Im trying to convert it to plotly with ggplotly() it does not respond. Anybody knows how to make the conversion?

output$energy_hour<-renderPlot({
        # all levels
    xlab <- seq(1, 24, 1/res)
    xpos <- seq(1, 24*res, 1)
    tab  <- table(eny_subs()$energy, factor(eny_subs()$hour, levels=xlab))
    tab  <- prop.table(tab, margin=2)
    barplot(tab, col=cols_energy, border="white", las=1, family="Corbel", ylab="aantal", xlab="uur", legend=TRUE,
        main="energie per uur", ylim=range(pretty(c(0, colSums(tab))))
        )
    grid(nx=0, ny=NULL)
    barplot(tab, col=cols_energy, border="white", las=1, family="Corbel", ylab="aantal", xlab="uur", legend=TRUE,
        main="energie per uur", ylim=range(pretty(c(0, colSums(tab)))), add=TRUE
        )


})

plotOutput("energy_hour")

Im using:


#################################### HOURS #####################################


output$energy_hour<-renderPlotly({
        # all levels
    xlab <- seq(1, 24, 1/res)
    xpos <- seq(1, 24*res, 1)
    tab  <- table(eny_subs()$energy, factor(eny_subs()$hour, levels=xlab))
    tab  <- prop.table(tab, margin=2)

   p1<- ggplot(tab, col=cols_energy, border="white", las=1, family="Corbel", ylab="aantal", xlab="uur", legend=TRUE,
        main="energie per uur", ylim=range(pretty(c(0, colSums(tab))))
        )
    grid(nx=0, ny=NULL)
   p1<- ggplot(tab, col=cols_energy, border="white", las=1, family="Corbel", ylab="aantal", xlab="uur", legend=TRUE,
        main="energie per uur", ylim=range(pretty(c(0, colSums(tab)))), add=TRUE
        )

ggplotly(p1)
})

plotlyOutput("energy_hour")

but I take: ggplot2 doesn't know how to deal with data of class table


#2

You appear to be using base plots, rather than ggplot.


#3

so what may be the solution?Im new to this


#4

Well, if you want to use ggplotly, you'll have to generate ggplot objects instead of base ones.

If you are happy with base plots, then you can use plotly directly (without ggplotly).


#5

I edited my question.


#6

The input must be a dataframe (or tibble, etc.).


#7

So I just have to convert tab to dataframe?


#8

Yes, but I've just taken a look at your ggplot calls and these are not correct.

Check the ggplot syntax here:
http://ggplot2.tidyverse.org/reference/ggplot.html


#9

I see.. a minimal working example would help.


#10

Several of the Shiny plotly examples use ggplot and ggplotly. e.g.