Arrange 4 plotly pie graphs in R - r

I have four separate pie graphs all with the same specified color scheme (the code is identical apart from the dataframe).
The colors are designated because I want to combine them in the 4 grid graph with one legend using the same designated colors for each of the 5 groups (ie. when the colors are not designated, the colors are automatically allocated based on the size of the group).
Example Data:
# Data
g = c("D","L","X","A","N","B")
v = c(49,14,9,7,6,5)
df1 = data.frame(group = g, value = v)
set.seed(9) # Just for reproductibility
df2 = data.frame(group = sample(g,size = nrow(df1),replace = F),
value = sample(v,size = nrow(df1),replace = F)
)
set.seed(8)
df3 = data.frame(group = sample(g,size = nrow(df1),replace = F),
value = sample(v,size = nrow(df1),replace = F)
)
set.seed(7)
df4 = data.frame(group = sample(g,size = nrow(df1),replace = F),
value = sample(v,size = nrow(df1),replace = F)
)
The code:
BC <-
plot_ly(b_c, labels = ~group, values = ~value, marker = list(colors = c( '#2ca02c', '#d62728','#9467bd', '#FF7F0E', '#1F77B4')), type = 'pie',textposition = 'outside',textinfo = 'label+percent') %>%
layout(title = 'b_c',autosize = F, width = 690, height = 690, margin = m,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
BC
I have reviewed these posts, but have not been able to determine an answer for combing the plots from these.
Subplots deploying in R Plotly
Plotting multiple pie charts in plotly
I am looking for something similar to ggarrange in ggplot
I have four sets of data, some of which have the same groups (ie. the same row names). For these I would like to use the same color.
I don't really mind about the color scheme (ie. can be any color), but would like to have a unifying color legend for all 4 piegraphs.

Hi #sar give a look if it solves your problem:
library(plotly)
library(dplyr)
# Data
g = c("D","L","X","A","N","B")
v = c(49,14,9,7,6,5)
df1 = data.frame(group = g, value = v)
set.seed(9) # Just for reproductibility
df2 = data.frame(group = sample(g,size = nrow(df1),replace = F),
value = sample(v,size = nrow(df1),replace = F)
)
set.seed(8)
df3 = data.frame(group = sample(g,size = nrow(df1),replace = F),
value = sample(v,size = nrow(df1),replace = F)
)
set.seed(7)
df4 = data.frame(group = sample(g,size = nrow(df1),replace = F),
value = sample(v,size = nrow(df1),replace = F)
)
#Plot
plot_ly(labels = ~group, values = ~value, legendgroup = ~group,
textposition = 'outside',textinfo = 'label+percent') %>%
add_pie(data = df1, name = "DF1", domain = list(row = 0, column = 0))%>%
add_pie(data = df2, name = "DF2", domain = list(row = 0, column = 1))%>%
add_pie(data = df3, name = "DF3", domain = list(row = 1, column = 0))%>%
add_pie(data = df4, name = "DF4", domain = list(row = 1, column = 1))%>%
layout(title = "Pie Charts in Grid", showlegend = T,
grid=list(rows=2, columns=2),
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
The Output:
EDIT1:
To show "subtitles" for each pie you can use annotations, you can also change the the legend position. The drawnback of annotations is that you must specify the position(mannualy in this case).
For avoid overlaping I suggest remove textposition = 'outside'.
You can download the plot as .png with the button on top right of the plot.
#Plot
plot_ly(labels = ~group, values = ~value, legendgroup = ~group,
textinfo = 'label+percent') %>%
add_pie(data = df1, name = "DF1", domain = list(row = 0, column = 0))%>%
add_pie(data = df2, name = "DF2", domain = list(row = 0, column = 1))%>%
add_pie(data = df3, name = "DF3", domain = list(row = 1, column = 0))%>%
add_pie(data = df4, name = "DF4", domain = list(row = 1, column = 1))%>%
layout(title = "Pie Charts in Grid", showlegend = T,
grid=list(rows=2, columns=2),
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
legend = list(y = 0.5),
annotations = list(x = c(.08, .62, .08, .62),
y = c(.78, .78, .22, .22),
text = c("Pie 1","Pie 2","Pie 3","Pie 4"),
xref = "papper",
yref = "papper",
showarrow = F
)
)
The new output is:
EDIT2:
Give a look in font or text font.
You can change text and hover text as you please with a template.
Here is an edit suggesting taking off the labels to get more space for percentage and rounding percentage to 1 decimal digit:
#Plot
plot_ly(labels = ~group, values = ~value, legendgroup = ~group, textinfo = 'label+percent',
texttemplate = "%{percent:.1%}",
hovertemplate = "%{label} <br> %{percent:.1%} <br> %{value}") %>%
add_pie(data = df1, name = "DF1", domain = list(row = 0, column = 0))%>%
add_pie(data = df2, name = "DF2", domain = list(row = 0, column = 1))%>%
add_pie(data = df3, name = "DF3", domain = list(row = 1, column = 0))%>%
add_pie(data = df4, name = "DF4", domain = list(row = 1, column = 1))%>%
layout(title = "Pie Charts in Grid", showlegend = T,
grid=list(rows=2, columns=2),
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
legend = list(y = 0.5),
annotations = list(x = c(.08, .62, .08, .62),
y = c(.78, .78, .22, .22),
text = c("Pie 1","Pie 2","Pie 3","Pie 4"),
xref = "papper",
yref = "papper",
showarrow = F
)
)
New Output:

Related

Titles in plotly subplots using grid

I'm trying to apply the solution for having titles in a plotly subplot to a plotly grid using this Subplots Using Grid example:
library(plotly)
library(dplyr)
f <- list(family="Courier New, monospace",size = 18,color = "black")
fig <- plot_ly()
fig <- fig %>% add_pie(data = count(diamonds, cut), labels = ~cut, values = ~n,
name = "Cut", domain = list(row = 0, column = 0)) %>%
layout(annotations=list(text = "Cut",font = f,xref = "paper",yref = "paper",yanchor = "bottom",xanchor = "center",align = "center",x = 0.5,y = 1,showarrow = FALSE))
fig <- fig %>% add_pie(data = count(diamonds, color), labels = ~color, values = ~n,
name = "Color", domain = list(row = 0, column = 1)) %>%
layout(annotations=list(text = "Color",font = f,xref = "paper",yref = "paper",yanchor = "bottom",xanchor = "center",align = "center",x = 0.5,y = 1,showarrow = FALSE))
fig <- fig %>% add_pie(data = count(diamonds, clarity), labels = ~clarity, values = ~n,
name = "Clarity", domain = list(row = 0, column = 2)) %>%
layout(annotations=list(text = "Clarity",font = f,xref = "paper",yref = "paper",yanchor = "bottom",xanchor = "center",align = "center",x = 0.5,y = 1,showarrow = FALSE))
fig <- fig %>% layout(showlegend = F,grid=list(rows=1, columns=3),
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
And what I'm getting is this:
Any idea?
You can use this code:
f <- list(family="Courier New, monospace",size = 18,color = "black")
fig <- plot_ly()
fig1 <- fig %>% add_pie(data = count(diamonds, cut), labels = ~cut, values = ~n,
name = "Cut", domain = list(row = 0, column = 0)) %>%
layout(annotations=list(text = "Cut",font = f,xref = "paper",yref = "paper",yanchor = "bottom",xanchor = "center",align = "center",x = 0.5,y = 1,showarrow = FALSE))
fig2 <- fig %>% add_pie(data = count(diamonds, color), labels = ~color, values = ~n,
name = "Color", domain = list(row = 0, column = 1)) %>%
layout(annotations=list(text = "Color",font = f,xref = "paper",yref = "paper",yanchor = "bottom",xanchor = "center",align = "center",x = 0.5,y = 1,showarrow = FALSE))
fig3 <- fig %>% add_pie(data = count(diamonds, clarity), labels = ~clarity, values = ~n,
name = "Clarity", domain = list(row = 0, column = 2)) %>%
layout(annotations=list(text = "Clarity",font = f,xref = "paper",yref = "paper",yanchor = "bottom",xanchor = "center",align = "center",x = 0.5,y = 1,showarrow = FALSE))
fig <- fig %>% layout(showlegend = F,grid=list(rows=1, columns=3),
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
p <- subplot(fig1, fig2, fig3, titleX = TRUE, titleY = TRUE) %>%
layout(showlegend = FALSE, grid=list(rows=1, columns=3),
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
p
Output:

Plotly: dual y axis graph messing up line graph

I'm trying to make a dual axis plot of rainfall and temperature. I have ordered the months on the bottom, but that causes my line graph to screw up. How do I make sure the added line uses the same x axis?
temprain<-data.frame(month = c(1:12),
Train = c(250,220, 180,97,38,27,31,47,70,140,200,250),
Tair = c(17,16, 15,13,9,6,5,9,12,13,14,16))
tempseq<-seq(0,20,by=0.5)
rainseq<-seq(0,260,by=1)
xlab<-list(type = "category",
categoryorder = "array",
categoryarray = month.name,
showgrid = TRUE,
showline = TRUE,
autorange = TRUE,
showticklabels = TRUE,
ticks = "outside",
tickangle = 0
)
plot_ly(temprain) %>%
add_bars(x = ~MonthName, y = ~Train, type = "bar", name = "Rain") %>%
add_lines(x = ~MonthName, y = ~Tair, yaxis = "y2", name = "Temp") %>%
layout(xaxis = xlab,
yaxis = list(showline = TRUE, side = "left",
title = "Rainfall (mm)Temp", range = tempseq),
yaxis2 = list(showline = TRUE, side = "right",
overlaying = "y", title = "Air Temp (C)", range = rainseq),
showlegend = FALSE,
margin = list(pad = 0, b = 50, l = 50, r = 50))
I tried this as well, and it doesn't work, the temp graph disappears
plot_ly(temprain, x = ~MonthName, y = ~Tair, name = "Temp") %>%
add_bars(x = ~MonthName, y = ~Train, yaxis = "y2", type = "bar", name = "Rain") %>%
layout(xaxis = xlab,
yaxis = list(showline = TRUE, side = "left",
title = "Air Temp (C)", range = tempseq),
yaxis2 = list(showline = TRUE, side = "right",
overlaying = "y",
title = "Rainfall (mm)", range = rainseq),
showlegend = FALSE,
margin = list(pad = 0, b = 50, l = 50, r = 50))
Below is the solution:
Your data:
temprain<-data.frame(month = c(1:12),
Train = c(250,220, 180,97,38,27,31,47,70,140,200,250),
Tair = c(17,16, 15,13,9,6,5,9,12,13,14,16))
Generate a column for month abbreviations from month:
mymonths <- c("Jan","Feb","Mar",
"Apr","May","Jun",
"Jul","Aug","Sep",
"Oct","Nov","Dec")
# match the month numbers against abbreviations:
temprain$MonthAbb = mymonths[ temprain$month ]
# This is the code to archieving a consistent combined graph:
temprain$MonthAbb <- factor(temprain$MonthAbb, levels = c(as.character(temprain$MonthAbb)))
Now plot your data:
fig <- plot_ly(temprain)
# Add the Train trace:
fig <- fig %>% add_trace(x = ~MonthAbb, y = ~Train, name = "Train", type = "bar")
ay <- list(
tickfont = list(color = "red"),
overlaying = "y",
side = "right",
title = "<b>Tair</b>")
# Add the Tair trace:
fig <- fig %>% add_trace(x = ~MonthAbb, y = ~Tair, name = "Tair", yaxis = "y2", mode = "lines+markers", type = "scatter")
fig <- fig %>% layout(yaxis2 = ay,
xaxis = list(title="Month"),
yaxis = list(title="<b>Train</b>"))%>%
layout(xaxis = list(
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff')
)
fig
Output:

Decrease the distance between bars in plotly while keeping them slim with bargap

I have used bargap to decrease the width of bars in plotly but I want to bring themcloser whild keeping this width and not make them thicker.
library(tidyr)
library(stringr)
library(forcats)
library(plotly)
# data
Category<-c("First dose","Full vaccination")
`Uptake first dose`<-c(19.8,0)
`Uptake full vaccination`<-c(0,7.6)
`Not vaccinated`<-c(80.2,92.4)
ch5<-data.frame(Category,`Uptake first dose`,`Uptake full vaccination`,`Not vaccinated`)
# transform data
data.long <- ch5 %>%
pivot_longer(cols = -Category,
names_to = "vac",
values_to = "percent") %>%
mutate(vac = str_replace_all(vac, "\\.", " "),
vac = fct_rev(factor(vac)))
library(plotly)
plot_ly(data.long) %>%
add_bars(y = ~Category,
x = ~percent,
color = ~vac,
text = ~vac,
colors = c("#458d35", "#63bb47", "#e6e7e8"),
hovertemplate = paste('<b>%{y}</b>',
'<br>%{text}: %{x} ',
'<extra></extra>')) %>%
layout(font = list(color = '#a2a2a2'),barmode = "stack",
bargap = 0.7,
yaxis = list(fixedrange = TRUE,autorange="reversed",
title = "",
showticklabels = FALSE,
showgrid = FALSE,
showline = FALSE,
zeroline = FALSE),
xaxis = list(fixedrange = TRUE,title = "",ticksuffix = '%',
zeroline = FALSE,
showgrid = FALSE),
hoverlabel = list(bgcolor = "black",
bordercolor = "black",
font = list(color = "white")),
shapes = list(type = "line",
y0 = 0, y1 = 1, yref = "paper",
x0 = 70, x1 = 70),
annotations = list(text = "Target (70%)",
showarrow = FALSE,
x = 70,
y = 1.05,
yref = "paper"),
legend = list(orientation = 'h'))

Switch displayed traces via plotly dropdown menu

I am working with the R programming language. I am trying to replicate this tutorial over here for my own data: https://plotly.com/r/dropdowns/
I created some fake data and made 4 plots:
#load libraries
library(plotly)
library(MASS)
library(dplyr)
# create data
x <- sample( LETTERS[1:4], 731, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
y <- rnorm(731,10,10)
z <- rnorm(731,5,5)
date= seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")
df <- data.frame(x,y, z, date)
df$x = as.factor(df$x)
# plot 1 : time series
aggregate = df %>%
mutate(date = as.Date(date)) %>%
group_by(month = format(date, "%Y-%m")) %>%
summarise( mean = mean(y))
ts_1 <- ggplot(aggregate) + geom_line(aes(x = month, y = mean, group = 1)) + theme(axis.text.x = element_text(angle = 90)) + ggtitle("time series 1")
plot_1 = ggplotly(ts_1)
#plot 2 : box plot
plot_2 <- plot_ly(df, y = ~y, color = ~x, type = "box") %>% layout(title = "boxplot")
#plot 3, 4 : scatter plots
df_1 <- df[which(df$x == "A"),]
df_2 <- df[which(df$x == "B"),]
plot_3 <- plot_ly( data = df_1, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 3")
plot_4 <- plot_ly( data = df_2, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 4")
Once these 4 plots have been created, I know how to save them together:
sub = subplot(plot_1, plot_2, plot_3, plot_4, nrows = 2)
#view result
sub
Now what I am trying to do, is have the user "toggle" (switch) between these graphs (as seen here: https://plotly.com/r/dropdowns/)
In a previous post (R: Switching Between Graphs ), I learned how to "glue" similar graphs together (e.g. 4 scatter plots). Now, I am trying to do so with different graphs (2 scatter plots, 1 time series and 1 box plot). I tried to adapt the code from the previous post to suit my example:
fig <- df %>%
add_trace(name = "A", plot_1) %>%
add_trace (name = "B" , df, y = ~y, color = ~x, type = "box") %>% layout(title = "boxplot")
add_trace (name = "C" , data = df_1, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 3") %>%
add_trace( name = "D", data = df_2, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 4") %>%
layout(xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = list(
list(method = "restyle",
args = list("visible", list(TRUE, FALSE, FALSE, FALSE)),
label = "A"),
list(method = "restyle",
args = list("visible", list(FALSE, TRUE, FALSE, FALSE)),
label = "B"),
list(method = "restyle",
args = list("visible", list(FALSE, FALSE, TRUE, FALSE)),
label = "C"),
list(method = "restyle",
args = list("visible", list(FALSE, FALSE, FALSE, TRUE)),
label = "D")))))
But this produces the following errors:
Error: $ operator is invalid for atomic vectors
Error in add_data(p, data) : argument "p" is missing, with no default
Can someone please show me if it is possible to fix this problem? Instead of using the "add_trace" approach, is it somehow possible to individually call each plotly graph object by its name (e.g. subplot(plot_1, plot_2, plot_3, plot_4, nrows = 2)), "glue" all the graphs together, and then add a "toggle button" that lets the user switch between them?
(note: I need to be able to save the final result as a "html" file)
Thanks
First of all, you should take care about plots which add multiple traces (see nTracesA etc.)
Besides changing the trace visibility you'll need to seperate categorial and numerical data onto separate x and y-axes and manage their visibility, too (see xaxis2, xaxis3, xaxis4 - this also works with a single y-axis but in this case the grid isn't displayed properly)
As described in the docs:
The updatemenu method determines which plotly.js function will be used
to modify the chart. There are 4 possible methods:
"restyle": modify data or data attributes
"relayout": modify layout attributes
"update": modify data and layout attributes
"animate": start or pause an animation (only available offline)
Accordingly the following, is using the update method (a lot of repition here - needs some cleanup, but I think it's better to understand this way):
# load libraries
library(dplyr)
library(plotly)
# create data
x <- sample(LETTERS[1:4],
731,
replace = TRUE,
prob = c(0.25, 0.25, 0.25, 0.25))
y <- rnorm(731, 10, 10)
z <- rnorm(731, 5, 5)
date <- seq(as.Date("2014/1/1"), as.Date("2016/1/1"), by = "day")
df <- data.frame(x, y, z, date)
df$x = as.factor(df$x)
nTracesA <- nTracesC <- nTracesD <- 1
nTracesB <- length(unique(df$x))
plotA <- plot_ly(data = df %>%
mutate(date = as.Date(date)) %>%
group_by(month = format(date, "%Y-%m")) %>%
summarise(mean = mean(y)),
type = 'scatter', mode = 'lines', x= ~ month, y= ~ mean, name = "plotA", visible = TRUE, xaxis = "x", yaxis = "y")
plotAB <- add_trace(plotA, data = df, x = ~x, y = ~y, color = ~ x, name = ~ paste0("plotB_", x),
type = "box", xaxis = "x2", yaxis = "y2", visible = FALSE, inherit = FALSE)
plotABC <- add_trace(plotAB, data = df[which(df$x == "A"),],
type = "scatter", mode = "markers", x = ~ y, y = ~ z,
name = "plotC", xaxis = "x3", yaxis = "y3", visible = FALSE, inherit = FALSE)
plotABCD <- add_trace(plotABC, data = df[which(df$x == "B"),], x = ~ y, y = ~ z,
type = "scatter", mode = "markers", name = "plotD", xaxis = "x4", yaxis = "y4", visible = FALSE, inherit = FALSE)
fig <- layout(plotABCD, title = "Initial Title",
xaxis = list(domain = c(0.1, 1), visible = TRUE, type = "date"),
xaxis2 = list(overlaying = "x", visible = FALSE),
xaxis3 = list(overlaying = "x", visible = FALSE),
xaxis4 = list(overlaying = "x", visible = FALSE),
yaxis = list(title = "y"),
yaxis2 = list(overlaying = "y", visible = FALSE),
yaxis3 = list(overlaying = "y", visible = FALSE),
yaxis4 = list(overlaying = "y", visible = FALSE),
updatemenus = list(
list(
y = 0.7,
buttons = list(
list(label = "A",
method = "update",
args = list(list(name = paste0("new_trace_name_", 1:7), visible = unlist(Map(rep, x = c(TRUE, FALSE, FALSE, FALSE), each = c(nTracesA, nTracesB, nTracesC, nTracesD)))),
list(title = "title A",
xaxis = list(visible = TRUE),
xaxis2 = list(overlaying = "x", visible = FALSE),
xaxis3 = list(overlaying = "x", visible = FALSE),
xaxis4 = list(overlaying = "x", visible = FALSE),
yaxis = list(visible = TRUE),
yaxis2 = list(overlaying = "y", visible = FALSE),
yaxis3 = list(overlaying = "y", visible = FALSE),
yaxis4 = list(overlaying = "y", visible = FALSE)))
),
list(label = "B",
method = "update",
args = list(list(visible = unlist(Map(rep, x = c(FALSE, TRUE, FALSE, FALSE), each = c(nTracesA, nTracesB, nTracesC, nTracesD)))),
list(title = "title B",
xaxis = list(visible = FALSE),
xaxis2 = list(overlaying = "x", visible = TRUE),
xaxis3 = list(overlaying = "x", visible = FALSE),
xaxis4 = list(overlaying = "x", visible = FALSE),
yaxis = list(visible = FALSE),
yaxis2 = list(overlaying = "y", visible = TRUE),
yaxis3 = list(overlaying = "y", visible = FALSE),
yaxis4 = list(overlaying = "y", visible = FALSE)))),
list(label = "C",
method = "update",
args = list(list(visible = unlist(Map(rep, x = c(FALSE, FALSE, TRUE, FALSE), each = c(nTracesA, nTracesB, nTracesC, nTracesD)))),
list(title = "title C",
xaxis = list(visible = FALSE),
xaxis2 = list(overlaying = "x", visible = FALSE),
xaxis3 = list(overlaying = "x", visible = TRUE),
xaxis4 = list(overlaying = "x", visible = FALSE),
yaxis = list(visible = FALSE),
yaxis2 = list(overlaying = "y", visible = FALSE),
yaxis3 = list(overlaying = "y", visible = TRUE),
yaxis4 = list(overlaying = "y", visible = FALSE)))),
list(label = "D",
method = "update",
args = list(list(visible = unlist(Map(rep, x = c(FALSE, FALSE, FALSE, TRUE), each = c(nTracesA, nTracesB, nTracesC, nTracesD)))),
list(title = "title D",
xaxis = list(visible = FALSE),
xaxis2 = list(overlaying = "x", visible = FALSE),
xaxis3 = list(overlaying = "x", visible = FALSE),
xaxis4 = list(overlaying = "x", visible = TRUE),
yaxis = list(visible = FALSE),
yaxis2 = list(overlaying = "y", visible = FALSE),
yaxis3 = list(overlaying = "y", visible = FALSE),
yaxis4 = list(overlaying = "y", visible = TRUE))))
))))
print(fig)
# htmlwidgets::saveWidget(partial_bundle(fig), file = "fig.html", selfcontained = TRUE)
# utils::browseURL("fig.html")
Some related info:
https://plotly.com/r/custom-buttons/
https://plotly.com/r/multiple-axes/
This is just a guess from the documentation but there is no add_data() call so maybe try this for your first line:
fig <- plot_ly() %>% add_data(df) %>%
See docs example:
plot_ly() %>% add_data(economics) %>% add_trace(x = ~date, y = ~pce)
A user on the Rstudio community forum provided an answer : https://community.rstudio.com/t/gluing-graphs-together-switch-toggle-between-graphs-in-r-plotly/95891/3
I am still trying to figure out how to format the axis - maybe someone could take a look at this?
#load libraries
library(plotly)
library(MASS)
library(dplyr)
# create data
x <- sample( LETTERS[1:4], 731, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
y <- rnorm(731,10,10)
z <- rnorm(731,5,5)
date= seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")
df <- data.frame(x,y, z, date)
df$x = as.factor(df$x)
# plot 1 : time series
aggregate = df %>%
mutate(date = as.Date(date)) %>%
group_by(month = format(date, "%Y-%m")) %>%
summarise( mean = mean(y))
ts_1 <- ggplot(aggregate) + geom_line(aes(x = month, y = mean, group = 1)) + theme(axis.text.x = element_text(angle = 90)) + ggtitle("time series 1")
plot_1 = ggplotly(ts_1)
#plot 2 : box plot
plot_2 <- plot_ly(df, y = ~y, color = ~x, type = "box") %>% layout(title = "boxplot")
#plot 3, 4 : scatter plots
df_1 <- df[which(df$x == "A"),]
df_2 <- df[which(df$x == "B"),]
plot_3 <- plot_ly( data = df_1, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 3")
plot_4 <- plot_ly( data = df_2, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 4")
fig = plot_ly()
fig = fig %>% add_trace(data = df %>%
mutate(date = as.Date(date)) %>%
group_by(month = format(date, "%Y-%m")) %>%
summarise( mean = mean(y)), type = 'scatter', mode = 'lines', x= ~month, y= ~mean,
name = "timeseries")
fig = fig %>% add_trace(data = df[which(df$x == "A"),], y = ~y, color = ~x,
type = "box", name = "boxplot")
fig = fig %>% add_trace( data = df[which(df$x == "B"),],
type = "scatter", mode = "markers", x = ~ y, y = ~z,
name= "graph2")
fig = fig %>% add_trace(data = df[which(df$x == "A"),], y = ~y, color = ~x,
type = "box", name = "boxplot2")
fig %>% layout(xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = list(
list(method = "restyle",
args = list("visible", list(TRUE, FALSE, FALSE, FALSE)),
label = "A"),
list(method = "restyle",
args = list("visible", list(FALSE, TRUE, FALSE, FALSE)),
label = "B"),
list(method = "restyle",
args = list("visible", list(FALSE, FALSE, TRUE, FALSE)),
label = "C"),
list(method = "restyle",
args = list("visible", list(FALSE, FALSE, FALSE, TRUE)),
label = "D")))))

Two X-axis in Plotly for R

https://community.plot.ly/t/how-to-plot-multiple-x-axis-in-plotly-in-r/3014/3?u=him4u324
I have posted my question on Plotly community as well
I am trying to display two x-axis with common Y-axis on plotly for R. I was able to do so as well but starting point for each x-axis is separated from each other Whereas I wish them to be represented a common y-axis.
f1 <- list(
family = "Arial, sans-serif",
size = 18,
color = "grey"
)
f2 <- list(
family = "Old Standard TT, serif",
size = 14,
color = "#4477AA"
)
# bottom x-axis
ax <- list(
title = "Number of PBIs",
titlefont = f1,
anchor = "y",
side = "bottom",
showticklabels = TRUE,
tickangle = 0,
tickfont = f2
)
# top x-axis
ax2 <- list(
title = " ",
overlaying = "x",
anchor = "y",
side = "top",
titlefont = f1,
showticklabels = TRUE,
tickangle = 0,
tickfont = f2
)
# common y-axis
ay <- list(
title = "Process & Sub-Process Areas",
titlefont = f1,
showticklabels = TRUE,
tickangle = 0,
tickfont = f2
)
plot_ly(data = scrum %>%
group_by(Master.Project) %>%
summarise(Total_PBIs_Planned=sum(PBIs.Planned.in.Sprint, na.rm = TRUE),
Total_PBIs_Delivered = sum(Actual.PBI.Delivery,na.rm = TRUE)) %>% inner_join(scrum %>% count(Master.Project)), # creating the desired data frame
color = I("#149EF7")) %>%
# for bottom x-axis
add_segments(x = ~Total_PBIs_Planned, xend = ~Total_PBIs_Delivered,
y = ~Master.Project, yend = ~Master.Project, showlegend = FALSE) %>%
add_trace(x = ~Total_PBIs_Planned, y = ~Master.Project,
name = "Total_PBIs_Planned", type = 'scatter',mode = "markers",
marker = list(color = "#149EF7", size = 15,
line = list(color = '#FFFFFF', width = 1))) %>%
add_trace(x = ~Total_PBIs_Delivered, y = ~Master.Project,
name = "Total_PBIs_Delivered",type = 'scatter',mode = "markers",
marker = list(symbol ="circle-dot",color = "#F71430", size = 10,
line = list(color = '#FFFFFF', width = 1))) %>%
# for top x-axis
add_trace(x = ~n, y = ~Master.Project, xaxis = "x2",
name = "No._of_Sub_projects",type = 'bar',
marker = list(color = "#149EF7"),
opacity = 0.1,
hoverinfo = 'text',
text = ~paste(
Master.Project,
'<br> Total Sub Projects: ',n,
'<br> PBIs Planned: ',Total_PBIs_Planned,
'<br> PBIs Delivered: ',Total_PBIs_Delivered
)
) %>%
plotly::layout(
title = "Product Backlog Items - Planned Vs Delivered", titlefont = f1,
xaxis = ax,
yaxis = ay,
xaxis2 = ax2,
margin = list(l = 250)
)
You want to use rangemode = "tozero" in your axis layout.
ax <- list(
title = "Number of PBIs",
titlefont = f1,
anchor = "y",
side = "bottom",
showticklabels = TRUE,
tickangle = 0,
tickfont = f2,
rangemode = 'tozero')
Or you can specify your specific ranges using
range = c(0, 5)
See Plotly help here: https://plot.ly/r/axes/#rangemode

Resources