Reputation: 1000
I am trying to create interactive ggplot2
s. manipulateWidget
doesn't seem to cut it (example below), or does it?
library(manipulateWidget)
library(plotly)
library(ggplot2)
mydata <- data.frame(x = 1:100, y = rnorm(100))
myPlot <- function(type, lwd) {
if (type == "points") {
plot_ly(mydata, x= ~x, y = ~y, type = "scatter", mode = "markers")
} else {
plot_ly(mydata, x= ~x, y = ~y, type = "scatter", mode = "lines",
line = list(width = lwd))
}
}
myPlot("points")
manipulateWidget(
myPlot(type, lwd),
type = mwSelect(c("points", "lines"), "points"),
lwd = mwSlider(1, 10, 1, .display = type == "lines")
)
myggplot <- function(type, lwd) {
if (type == "points") {
ggplot(mydata, aes(x, y)) + geom_point()
} else {
ggplot(mydata, aes(x, y)) + geom_line(size = lwd)
}
}
myggplot("points")
manipulateWidget(
myggplot(type, lwd),
type = mwSelect(c("points", "lines"), "points"),
lwd = mwSlider(1, 10, 1, .display = type == "lines")
)
If that's true, what's are good alternatives?
Upvotes: 2
Views: 182
Reputation: 84719
A ggplot
object is not a htmlwidget, so that does not work. You can convert it to a htmlwidget with the ggiraph
package.
library(ggplot2)
library(ggiraph)
library(manipulateWidget)
myggplot <- function(type, lwd) {
if (type == "points") {
gg <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point_interactive()
} else {
gg <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_line_interactive(size = lwd)
}
girafe(ggobj = gg)
}
manipulateWidget(
myggplot(type, lwd),
type = mwSelect(c("points", "lines"), "points"),
lwd = mwSlider(1, 10, 1, .display = type == "lines")
)
Upvotes: 1