plotly subplot with ggplot and grouped legend? - r

I'm trying to arrange all the plots i.e. barplots that have a common legend in the plotly subplot. I have created individual subplot using ggplotly and hide_legend() doesn't seem to solve my problem. With plotly it is easier to do the same thing but I have to forget about ggplot. Can anyone help me in this matter?
Here is the code describing my problem:
library(dplyr)
library(ggplot2)
library(plotly)
data <- dget("loan_pred.data")
factor_col_names <- names(data)[map_lgl(data,is.factor)]
n<- 1
create_barplot_plotly <- function(feature){
g <- ggplot(data) +
aes_string(x=feature)+
ggtitle(paste(feature))+
geom_bar(aes(fill=Loan_Status),position = "fill")+
ylim(0,1+0.10)+
ylab("proportion") + theme_bw()
g <- ggplotly(g)
if (n %% length(factor_col_names)!=1){
g <- hide_legend(g)
}
n <<- n +1
return(g)
}
plotly::subplot(map(factor_col_names,create_barplot_plotly),
nrows = 3,margin = 0.06,titleX = TRUE,titleY = TRUE)%>%
layout(title="BoxPlots")
I have uploaded the data using dput on Google Drive and edited the code to reduce dependencies.

Related

How do I make grouped boxplots work in plotly?

I'd like to make a grouped boxplot in plotly in R, but it simply doesn't show up
I'm taking a boxplot that works in ggplot and trying to translate it to r
This is my code
library(fpp)
library(tidyverse)
library(plotly)
library(Hmisc)
gg <-
credit %>%
ggplot(aes(score,
group = cut2(savings, g = 4),
fill = cut2(savings, g = 4))) +
geom_boxplot() +
coord_flip()
ggplotly(gg)
It shows up really nicely in ggplot and then doesn't show at all in plotly

Understanding the layout of gtable: move panel and axis in odd ggplot layout

I am trying to alter the layout of a raster stack I plotted using ggplot. Below is a sample code to work with. Basically, I would like to move the facet labelled G (including the panel, x-axis and y-axis) into the empty facet.
library(raster)
# sample data to work with
r <- raster(ncol=10, nrow=10, vals=1:100)
r <- stack(replicate(7, r))
names(r) <- LETTERS[1:nlayers(r)]
coords <- xyFromCell(r, seq_len(ncell(r)))
dat <- stack(as.data.frame(getValues(r)))
names(dat) <- c('value', 'variable')
dat <- cbind(coords, dat)
# Plotting the raster stack using ggplot
p <- ggplot(dat, aes(x, y, fill = value))+
geom_raster() +
facet_wrap(~ variable, ncol = 2, as.table = TRUE)+
coord_equal()+
scale_fill_gradientn(colours = rev(terrain.colors(225))) +
theme(legend.position = 'none',
axis.title = element_blank())
p
This post solved a similar issue but I just can't understand it enough to make it work for my case. I also looked at the (Unofficial) overview of gtable but I only get confused about the layout specification. Therefore, I would like to have the job done but I would also appreciate long explanation, particularly about the layout in gtable.

Symmetrical histograms

I want to make a number of symmetrical histograms to show butterfly abundance through time. Here's a site that shows the form of the graphs I am trying to create: http://thebirdguide.com/pelagics/bar_chart.htm
For ease, I will use the iris dataset.
library(ggplot2)
g <- ggplot(iris, aes(Sepal.Width)) + geom_histogram(binwidth=.5)
g + coord_fixed(ratio = .003)
Essentially, I would like to mirror this histogram below the x-axis. Another way of thinking about the problem is to create a horizontal violin diagram with distinct bins. I've looked at the plotrix package and the ggplot2 documentation but don't find a solution in either place. I prefer to use ggplot2 but other solutions in base R, lattice or other packages will be fine.
Without your exact data, I can only provide an approximate coding solution, but it is a start for you (if you add more details, I'll be happy to help you tweak the plot). Here's the code:
library(ggplot2)
noSpp <- 3
nTime <- 10
d <- data.frame(
JulianDate = rep(1:nTime , times = noSpp),
sppAbundance = c(c(1:5, 5:1),
c(3:5, 5:1, 1:2),
c(5:1, 1:5)),
yDummy = 1,
sppName = rep(letters[1:noSpp], each = nTime))
ggplot(data = d, aes(x = JulianDate, y = yDummy, size = sppAbundance)) +
geom_line() + facet_grid( sppName ~ . ) + ylab("Species") +
xlab("Julian Date")
And here's the figure.

Moving table created by annotation_custom with geom_bar plot

I tried searching for answers but couldn't find anything.
I have have a plot and want to add a table within the plot itself. I can do it but the table ends up being right in the middle.
It is possible to relocate a table created by annotation_custom if the x-axis is discrete? If so, how?
Thank you!
For example, I want to relocate this table.
library(ggplot2)
library(gridExtra)
my.summary <- summary(chickwts$weight)
my.table <- data.frame(ids = names(my.summary), nums = as.numeric(my.summary))
ggplot(chickwts, aes(feed, weight)) +
geom_bar(stat = "identity") +
annotation_custom(tableGrob(my.table))
The custom annotation in ggplot2 can be rearragned inside the plotting area. This at least moves them out of the center. Maybe this solution is already sufficient for you. I'll try and tweak this. It should be possible to put this outside the plotting area as well.
library(ggplot2)
library(gridExtra)
my.summary <- summary(chickwts$weight)
my.table <- data.frame(ids = names(my.summary), nums = as.numeric(my.summary))
ggplot(chickwts, aes(feed, weight)) +
geom_bar(stat = "identity") +
annotation_custom(tableGrob(my.table), xmin=5,xmax=6,ymin=300,ymax=1300)
EDIT:
To place the table outside the plot, regardless of what the plot consists of, the grid package could be used:
library(ggplot2)
library(gridExtra)
library(grid)
# data
my.summary <- summary(chickwts$weight)
my.table <- data.frame(ids = names(my.summary), nums = as.numeric(my.summary))
# plot items
my.tGrob <- tableGrob(my.table)
plt <- ggplot(chickwts, aes(feed, weight)) +
geom_bar(stat = "identity")
# layout
vp.layout <- grid.layout(nrow=1, ncol=2, heights=unit(1, "null"),
widths=unit(c(1,9), c("null","line")) )
# start drawing
grid.newpage()
pushViewport(viewport(layout=vp.layout, name="layout"))
# plot
pushViewport(viewport(layout.pos.row=1, layout.pos.col=1, name="plot"))
print(plt, newpage=FALSE)
upViewport()
# table
pushViewport(viewport(layout.pos.row=1, layout.pos.col=2, name="table"))
grid.draw(my.tGrob)
upViewport()
#dev.off()

Add direct labels to ggplot2 geom_area chart

This is a continuation of the question here: Create non-overlapping stacked area plot with ggplot2
I have a ggplot2 area chart created by the following code. I want the labels from names be aligned on the right side of the graph. I think directlabels might work, but am willing to try whatever is most clever.
require(ggplot2)
require(plyr)
require(RColorBrewer)
require(RCurl)
require(directlabels)
link <- getURL("http://dl.dropbox.com/u/25609375/so_data/final.txt")
dat <- read.csv(textConnection(link), sep=' ', header=FALSE,
col.names=c('count', 'name', 'episode'))
dat <- ddply(dat, .(episode), transform, percent = count / sum(count))
# needed to make geom_area not freak out because of missing value
dat2 <- rbind(dat, data.frame(count = 0, name = 'lane',
episode = '02-tea-leaves', percent = 0))
g <- ggplot(arrange(dat2,name,episode), aes(x=episode,y=percent)) +
geom_area(aes(fill=name, group = name), position='stack') + scale_fill_brewer()
g1 <- g + geom_dl(method='last.points', aes(label=name))
I'm brand new to directlabels and not really sure how to get the labels to align to right side of the graph with the same colors as the areas.
You can use simple geom_text to add labels. First, subset you data set to get the final x value:
dd=subset(dat, episode=="06-at-the-codfish-ball")
Then order the data frame by factor level:
dd = dd[with(dd, order(name, levels(dd$name))),]
Then work out the cumulative percent for plotting:
dd$cum = cumsum(dd$percent)
Then just use a standard geom_text call:
g + geom_text(data=dd, aes(x=6, y=cum, label=name))
Oh, and you may want to angle your x-axis labels to avoid over plotting:
g + opts(axis.text.x=theme_text(angle=-25, hjust=0.5, size = 8))
Graph

Resources