I was a heavy rCharts
user, but nowadays, in my opinion, plotly
is a better supported option (rCharts
is not in CRAN anymore).
Furthermoreplotly
has an automatic way to make ggplot2
charts interactive. For your example:
library(ggplot2)
library(plotly)
df <- data.frame(
numbers = rep(1:3, 30),
letter = sample(c("A", "B", "C", "D"), 90, replace = TRUE),
status = sample(c("good", "bad", "ugly"), 90, replace = TRUE)
)
p <-
ggplot(df, aes(letter, fill = status)) + geom_bar() + facet_wrap(. ~ numbers)
ggplotly(p)
EDIT 1
This edit is made to suit the needs of the comment.
The changes you requested cannot be made directly from ggplot2
so you need to use plotly
. There may be a more elegant way to do the chart than my for loops but they seem to work:
library(data.table)
library(ggplot2)
library(plotly)
# make data.table
df <- data.table(
numbers = rep(1:3, 30),
letter = sample(c("A", "B", "C", "D"), 90, replace = TRUE),
status = sample(c("good", "bad", "ugly"), 90, replace = TRUE)
)
# keep unique status values for bars and numbers for facets
traces <- df[,unique(status)]
facets <- df[,unique(numbers)]
# cast df
casted_df <- dcast(df,letter + numbers ~ status )
# initialise list to keep charts
facetplots <- list()
for(i in 1:length(facets)){
# initialise chart
facetplots[[i]] <- plot_ly(type = "bar")
facet_df <- casted_df[numbers == facets[i]]
for(j in traces){
if(i == 1){
facetplots[[i]] <- add_trace(facetplots[[i]], x = facet_df[,letter], y = facet_df[,get(j)],legendgroup = j , color = j, name = j )
}else{
facetplots[[i]] <- add_trace(facetplots[[i]], x = facet_df[,letter], y = facet_df[,get(j)],legendgroup = j, color = j , name = j , showlegend = F)
}
}
facetplots[[i]] <- layout( facetplots[[i]], barmode = "stack")
}
q <- subplot(facetplots, shareX = TRUE)
q