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:
Related
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:
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'))
How can I add a horizontal x-axis scroll bar in a long plotly line chart?
library(plotly)
x <- c(1:100)
random_y <- rnorm(100, mean = 0)
data <- data.frame(x, random_y)
fig <- plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines')
fig
Case that rangeslider() does not work.
VaccinationWeek<-c("2020w1","2020w1","2020w1","2020w2","2020w2","2020w2")
Country<-c("EU","CHE","ITA","EU","CHE","ITA")
Value<-c(3,2,1,5,3,2)
dat<-data.frame(VaccinationWeek,Country,Value)
plot_ly(dat,
x = ~VaccinationWeek,
y = ~Value/100,
text = ~Value,
color = ~Country,
customdata = dat$Country) %>%
add_trace(
type = 'scatter',
mode = 'lines+markers',
hovertemplate = paste("Country: %{customdata}",
"Uptake full vaccination (%): %{y}",
"<extra></extra>",
sep = "\n"),
hoveron = 'points') %>%
add_text(
textposition = "top center",
showlegend = F,
hoverinfo = "skip") %>%
layout(font = list(color = '#a2a2a2'),title=list(text="by reporting week",x = 0),
xaxis = list(fixedrange = TRUE,title="",showgrid = FALSE,tickangle = 45
),
yaxis = list(fixedrange = TRUE,rangeslider = list(),title="",showgrid = FALSE,showline=T,tickformat = "%"),
hovermode = "x unified",
hoverlabel = "none",
legend = list(itemclick = F, itemdoubleclick = F))%>%
config(modeBarButtonsToRemove = c('toImage',"zoom2d","toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian","drawline","autoScale2d" ,"resetScale2d","zoomIn2d","zoomOut2d","pan2d",'select2d','lasso2d'))%>%
config(displaylogo = FALSE)
I'd suggest using a rangeslider:
library(plotly)
x <- c(1:100)
random_y <- rnorm(100, mean = 0)
data <- data.frame(x, random_y)
fig <- plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines') %>%
layout(xaxis = list(rangeslider = list()))
fig
After #firmo23's edit:
library(plotly)
VaccinationWeek <- c("2020w1", "2020w1", "2020w1", "2020w2", "2020w2", "2020w2")
Country <- c("EU", "CHE", "ITA", "EU", "CHE", "ITA")
Value <- c(3, 2, 1, 5, 3, 2)
dat <- data.frame(VaccinationWeek, Country, Value)
plot_ly(
dat, x = ~ VaccinationWeek, y = ~ Value / 100, text = ~ Value, color = ~ Country, customdata = dat$Country
) %>%
add_trace(
type = 'scatter', mode = 'lines+markers', hovertemplate = paste(
"Country: %{customdata}", "Uptake full vaccination (%): %{y}", "<extra></extra>", sep = "\n"
), hoveron = 'points'
) %>%
add_text(textposition = "top center", showlegend = F, hoverinfo = "skip") %>%
layout(
font = list(color = '#a2a2a2'), title = list(text = "by reporting week", x = 0), xaxis = list(
fixedrange = TRUE, title = "", showgrid = FALSE, tickangle = 45, rangeslider = list()
), yaxis = list(
fixedrange = TRUE, rangeslider = list(), title = "", showgrid = FALSE, showline = T, tickformat = "%"
), hovermode = "x unified", hoverlabel = "none", legend = list(itemclick = F, itemdoubleclick = F)
) %>%
config(
modeBarButtonsToRemove = c(
'toImage',
"zoom2d",
"toggleSpikelines",
"hoverClosestCartesian",
"hoverCompareCartesian",
"drawline",
"autoScale2d" ,
"resetScale2d",
"zoomIn2d",
"zoomOut2d",
"pan2d",
'select2d',
'lasso2d'
),
displaylogo = FALSE
)
I have the stacked bar below in which everything works fine except from the values in the axes and the hovertext which seem to have been multiplied by 100. I tried to to trick it by dividing my initial values with 100 but then I was taking rounded values back (20 instead of 19.8). I think that happened after I added tickformat=%
# 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)))
# add plot
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 = "",
tickformat = "%",
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'))
Use ticksuffix = '%'.
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'))
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: