Convert ggplot graph to plotly

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

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

so what may be the solution?Im new to this

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).

1 Like

I edited my question.

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

1 Like

So I just have to convert tab to dataframe?

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

Check the ggplot syntax here:

I see.. a minimal working example would help.

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