R plotly: How to connect lines on polar/radar chart? - r

I am creating a polar chart in R with plotly, but I don't want the values between lines to be filled with color. I found the line_close property for python library, but I can't find the equivalent in R.
Chart code:
library(plotly)
p <- plot_ly(
type = 'scatterpolar',
mode = 'lines',
) %>%
add_trace(
mode = 'lines',
r = c(3, 0, 1),
theta = c('A','B','C'),
name = '1'
) %>%
add_trace(
mode = 'lines',
r = c(1, 2, 3),
theta = c('A','B','C'),
name = '2'
) %>%
layout(
polar = list(
radialaxis = list(
angle = 90,
visible = T,
range = c(0,3),
showline = F,
color = '#bfbfbf',
nticks = 4,
tickangle = 90
)
)
)
p
Chart image:

I've had a good look through plotly::schema, and there doesn't seem to be an option to do this built in to the R port of plotly.
However, it is trivial to define your own add_closed_trace function like this:
add_closed_trace <- function(p, r, theta, ...)
{
plotly::add_trace(p, r = c(r, r[1]), theta = c(theta, theta[1]), ...)
}
You can use this as a drop-in for add_trace, like this:
library(plotly)
p <- plot_ly(
type = 'scatterpolar',
mode = 'lines',
) %>%
add_closed_trace(
mode = 'lines',
r = c(3, 0, 1),
theta = c('A','B','C'),
name = '1'
) %>%
add_closed_trace(
mode = 'lines',
r = c(1, 2, 3),
theta = c('A','B','C'),
name = '2'
) %>%
layout(
polar = list(
radialaxis = list(
angle = 90,
visible = T,
range = c(0,3),
showline = F,
color = '#bfbfbf',
nticks = 4,
tickangle = 90
)
)
)
p

Related

Adding a static element across slider steps in a R plotly graph

I am giving a tutorial on MLE and am trying to figure out how to add a static grouping of points to a plotly graph. Obviously the idea is that as I slide the normal distributions over you can see that the points correspond to a lower or higher likeihood. However, I can only get the points to appear on the first frame.
x <- seq(0, 10, length.out = 1000)
aval <- list()
for (step in 1:6) {
aval[[step]] <- list(
visible = FALSE,
name = paste0('v = ', step),
x = x,
y = dnorm(x, step+1)
)
}
aval[3][[1]]$visible = TRUE
steps <- list()
fig <- plot_ly()
for (i in 1:6) {
fig <-
add_lines(
fig,
x = aval[i][[1]]$x,
y = aval[i][[1]]$y,
visible = aval[i][[1]]$visible,
name = aval[i][[1]]$name,
type = 'scatter',
mode = 'lines',
hoverinfo = 'name',
line = list(color = '00CED1'),
showlegend = FALSE
)
step <- list(args = list('visible', rep(FALSE, length(aval))),method = 'restyle')
step$args[[2]][i] = TRUE
steps[[i]] = step
}
fig <- fig %>% add_markers(x = c(4.5,5,5.5), y = c(0,0,0))
# add slider control to plot
fig <- fig %>%
layout(sliders = list(list(
active = 0,
currentvalue = list(prefix = "Frequency: "),
steps = steps
)))
fig
Why don't you use plotly's animation capabilities?
But regardless of whether you define custom steps or you use the frame parameter, you'll have to provide the "static" points for each step:
library(plotly)
library(data.table)
f <- 1:6
x <- seq(0, 10, length.out = 1000)
y <- unlist(lapply(f+1, dnorm, x = x))
DT <- CJ(f, x) # like expand.grid()
DT[, y := y]
DT[, step := paste0("step-", f)]
staticDT <- CJ(f, x = c(4.5,5,5.5), y = 0)
staticDT[, step := paste0("step-", f)]
fig <- plot_ly(
data = DT,
x = ~x,
y = ~y,
frame = ~step,
type = 'scatter',
mode = 'lines',
showlegend = FALSE,
color = I('#00CED1')
)
fig <- add_trace(
fig,
data = staticDT,
x = ~x,
y = ~y,
frame = ~step,
type = 'scatter',
mode = 'markers',
showlegend = FALSE,
color = I('red'),
inherit = FALSE
)
fig <- animation_opts(
fig, transition = 0, redraw = FALSE
)
fig <- animation_slider(
fig, currentvalue = list(prefix = "Frequency: ")
)
fig

How can I add a subcategory to axis in Plotly with R?

I am trying to add a second category to x axis with Plotly under R like this:
Here is my code:
library(plotly)
data <- data.frame(day= c(1:4),
visit = c("visit1","visit1", "visit2", "visit2"),
val = c(1:4),
flag = c("","","", 1))
fig <- plot_ly(data= data, x = ~day) %>%
add_trace(y = ~val,
type = 'scatter',
mode = 'lines+markers',
line = list(width = 2,
dash = 'solid')) %>%
add_trace(data= data %>% filter(flag == 1), y = 0,
type = 'scatter',
hoverinfo = "text",
mode = 'markers',
name = "flag",
text = paste("<br>N°",data$ID[data$flag == 1],
"<br>Day",data$day[data$flag == 1]),
marker = list(
color = 'red',
symbol = "x",
size = 12
),
showlegend = T
)
fig
I have tried this, which seems good but the markers disappear from the graph, maybe due to the filter on data.
library(plotly)
data <- data.frame(day= c(1:4),
visit = c("visit1","visit1", "visit2", "visit2"),
val = c(1:4),
flag = c("","","", 1))
fig <- plot_ly(data= data, x = ~list(visit,day)) %>%
add_trace(y = ~val,
type = 'scatter',
mode = 'lines+markers',
line = list(width = 2,
dash = 'solid')) %>%
add_trace(data= data %>% filter(flag == 1), y = 0,
type = 'scatter',
hoverinfo = "text",
mode = 'markers',
name = "flag",
text = paste("<br>N°",data$ID[data$flag == 1],
"<br>Day",data$day[data$flag == 1]),
marker = list(
color = 'red',
symbol = "x",
size = 12
),
showlegend = T
)
fig
You didn't provide a reproducible question, so I've made data. (Well, data I shamelessly stole from here). This creates a bar graph with two sets of x-axis labels. One for each set of bars. One for each group of bars. The content of the x-axis is the same in both traces.
library(plotly)
fig <- plot_ly() %>%
add_bars(x = list(rep(c("first", "second"), each = 2),
rep(LETTERS[1:2], 2)),
y = c(2, 5, 2, 6),
name = "Adults") %>%
add_bars(x = list(rep(c("first", "second"), each = 2),
rep(LETTERS[1:2], 2)),
y = c(1, 4, 3, 6),
name = "Children")
fig
Update
You added data and code trying to apply this to your data. I added an update and apparently missed what the problem was. Sorry about that.
Now that I'm paying attention (let's hope, right?), here is an actual fix to the actual problem.
For this change, I modified your data. Instead of the flag annotated with a one, I changed it to zero. Then I used flag as a variable.
data <- data.frame(day = c(1:4),
visit = c("visit1","visit1", "visit2", "visit2"),
val = c(1:4),
flag = c("","","", 0))
fig <- plot_ly(data= data, x = ~list(visit,day)) %>%
add_trace(y = ~val,
type = 'scatter', mode = 'lines+markers',
line = list(width = 2,
dash = 'solid')) %>%
add_trace(y = ~flag,
type = 'scatter', hoverinfo = "text",
mode = 'markers', name = "flag",
text = paste("<br>N°",data$ID[data$flag == 1],
"<br>Day",data$day[data$flag == 1]),
marker = list(
color = 'red', symbol = "x", size = 12),
showlegend = T)
fig
You're going to get a warning about discrete & non-discrete data, which isn't really accurate, but it shows up, nonetheless.

R Plotly scatter ternary colorbar

I am using Plotly to make a scatter ternary plot. I want to color points by one of the values in the data frame (titled mu). However, the colorbar isn't showing. Here is my code:
library(plotly)
df <- eqData0
# axis layout
axis <- function(title) {
list(
title = title,
titlefont = list(
size = 20
),
tickfont = list(
size = 15
),
tickcolor = 'rgba(0,0,0,0)',
ticklen = 5
)
}
fig <- df %>% plot_ly()
fig <- fig %>% add_trace(
type = 'scatterternary',
mode = 'markers',
a = ~u1eq,
b = ~u2eq,
c = ~bueq,
marker = list(
symbol = 100,
color = ~mu,
size = 14,
line = list('width' = 2),
colorscale = 'YlGnBu'
),
colorbar = list(
xanchor = 'middle',
yanchor = 'middle'
)
)
m <- list(
l = 50,
r = 50,
b = 100,
t = 100,
pad = 4
)
fig <- fig %>% layout(autosize = F, width = 500, height = 500, margin = m,
ternary = list(
sum = 1,
aaxis = axis(TeX("$u_1$")),
baxis = axis(TeX("$u_2$")),
caxis = axis(TeX("$\\bar{u}$"))
)
)
fig <- fig %>% config(mathjax = 'cdn')
fig
Somehow the colorbar is still not showing! I'm not sure why because all the Plotly scatterplot examples online make getting the colorbar to show up seem easy.
It looks like you were missing showscale=TRUE in the trace definition.
Trying:
#fake data:
df <- data.frame(u1eq = c(0.2, 0.3, 0.5), u2eq=c(0.6, 0.3, 0.1), bueq=c(0.2, 0.4, 0.4), mu=c(1, 1.8, 2))
# axis layout
axis <- function(title) {
list(
title = title,
titlefont = list(
size = 20
),
tickfont = list(
size = 15
),
tickcolor = 'rgba(0,0,0,0)',
ticklen = 5
)
}
fig <- df %>% plot_ly()
fig <- fig %>% add_trace(
type = 'scatterternary',
mode = 'markers',
a = ~u1eq,
b = ~u2eq,
c = ~bueq,
marker = list(
colorscale = 'YlGnBu',
symbol = 100,
color = ~mu,
size = 14,
line = list('width' = 2),
showscale = TRUE
)
)
m <- list( l = 50, r = 50, b = 100, t = 100, pad = 4)
fig <- fig %>% layout(autosize = F, width = 500, height = 500, margin = m,
ternary = list(
sum = 1,
aaxis = axis(TeX("$u_1$")),
baxis = axis(TeX("$u_2$")),
caxis = axis(TeX("$\\bar{u}$")) )
) %>% config(mathjax = 'cdn')
fig

Set text size within marker in r plotly bubble chart

The labels within bubbles are appearing with size proportional to size argument. However I want to keep the labels in constant sizes.
Which argument should I use to keep them at constant size ?
Code that I am using is provided below.
df = data.frame( x = c( 3, 2, 2, 4, 6, 8 ), y = c( 3, 2, 3, 4, 6, 7 ), size = c( 20, 20, 20, 30, 40, 40 ), labels = letters[1:6] )
evo_bubble <- function(plot_data ,x_var, y_var, z_var, t_var) {
# Trasform data into dataframe and quos
df <- data.frame(plot_data)
xenc <- enquo(x_var)
yenc <- enquo(y_var)
zenc <- enquo(z_var)
tenc <- enquo(t_var)
df <- df %>% mutate( bubble_size = !!zenc*50 ) # Modify the denominator if you want to change the dimension of the bubble
# Set parameters for the plot
bubble_pal <- c("white", "#AECEE8" )
gray_axis <- '#dadada'
font_size <- list(size = 12, family = 'Lato')
width <- 0.5
legend_name <- Hmisc::capitalize( quo_name(zenc) ) # WATCH OUT! it works only with the package with Hmisc
decimal <- ',.2f'
sep <- ','
#x_name <- capitalize(quo_name(xenc))
y_name <- Hmisc::capitalize(quo_name(yenc))
p <- plot_ly(df, x = xenc, y = yenc, name = '', text = tenc, type = "scatter", mode = 'markers+text',
hoverlabel = list(font = font_size), size = zenc, color = zenc, hoverinfo = "text+y", colors= bubble_pal,
marker = list(size = df$bubble_size, line = list(color = gray_axis)) ) %>% hide_colorbar()
p <- p %>% layout(xaxis = list(zeroline = F,
title = '',
linecolor = gray_axis,
titlefont = font_size,
tickfont = font_size,
rangemode='tozero',
gridcolor = gray_axis,
gridwidth = width,
hoverformat = decimal,
mirror = "ticks",
tickmode = 'array',
tickcolor = gray_axis,
linewidth = width,
showgrid = F ),
yaxis = list(title = y_name,
zerolinecolor = gray_axis,
linecolor = gray_axis,
mirror = "ticks",
hoverformat = '.2f',
linewidth = width,
tickcolor = gray_axis,
tickformat = '.2f',
titlefont = font_size,
tickfont = font_size,
showgrid = FALSE) ) %>%
config(displayModeBar = F)
return(p)
}
evo_bubble( df, x, y, size, labels )
Expected image :
Obtained image :
Please ignore the colors in plot.
You can use add_text to get the desired result:
library(plotly)
library(dplyr)
DF = data.frame( x = c( 3, 2, 2, 4, 6, 8 ), y = c( 3, 2, 3, 4, 6, 7 ), size = c( 20, 20, 20, 30, 40, 40 ), labels = letters[1:6] )
evo_bubble <- function(plot_data, x_var, y_var, z_var, t_var) {
# browser()
# Trasform data into dataframe and quos
DF <- data.frame(plot_data)
xenc <- enquo(x_var)
yenc <- enquo(y_var)
zenc <- enquo(z_var)
tenc <- enquo(t_var)
DF <- DF %>% mutate( bubble_size = !!zenc*50 ) # Modify the denominator if you want to change the dimension of the bubble
# Set parameters for the plot
bubble_pal <- c("white", "#AECEE8" )
gray_axis <- '#dadada'
font_size <- list(size = 12, family = 'Lato')
width <- 0.5
legend_name <- Hmisc::capitalize( quo_name(zenc) ) # WATCH OUT! it works only with the package with Hmisc
decimal <- ',.2f'
sep <- ','
#x_name <- capitalize(quo_name(xenc))
y_name <- Hmisc::capitalize(quo_name(yenc))
p <- plot_ly(DF, x = xenc, y = yenc, name = '', type = "scatter", mode = 'markers',
hoverlabel = list(font = font_size), size = zenc, color = zenc, hoverinfo = "text+y", colors= bubble_pal,
marker = list(size = DF$bubble_size, line = list(color = gray_axis))) %>%
add_text(text = tenc, textfont = font_size, textposition = "middle center") %>% hide_colorbar()
p <- p %>% layout(xaxis = list(zeroline = F,
title = '',
linecolor = gray_axis,
titlefont = font_size,
tickfont = font_size,
rangemode='tozero',
gridcolor = gray_axis,
gridwidth = width,
hoverformat = decimal,
mirror = "ticks",
tickmode = 'array',
tickcolor = gray_axis,
linewidth = width,
showgrid = F ),
yaxis = list(title = y_name,
zerolinecolor = gray_axis,
linecolor = gray_axis,
mirror = "ticks",
hoverformat = '.2f',
linewidth = width,
tickcolor = gray_axis,
tickformat = '.2f',
titlefont = font_size,
tickfont = font_size,
showgrid = FALSE) ) %>%
config(displayModeBar = F)
return(p)
}
evo_bubble( DF, x, y, size, labels )

How to add Data markers in Waterfall chart in Plotly

I am trying to plot waterfall chart with the following code. The only issue I am facing currently is the data marker which is not at the correct place. I want the data marker to be just below the end of each bar.
source('./r_files/flatten_HTML.r')
library("plotly")
dataset <- data.frame(Category = c("Akash Jain","Ankit Jain","Pankaj Jain","Nitin Pandey","Gopal Pandit","Ramnath Agarwal"),
TH = c(-62,-71,-1010,44,-44,200))
#dataset <- data.frame(Category = Values$Category, TH = Values$TH)
#dataset <- as.data.frame(cbind(Values$Category,Values$TH))
dataset$Category = dataset$Category
dataset$TH = dataset$TH
dataset$SortedCategoryLabel <- sapply(dataset$Category, function(x) gsub(" ", " <br> ", x))
dataset$SortedCategory <- factor(dataset$SortedCategoryLabel, levels = dataset$SortedCategoryLabel)
dataset$id <- seq_along(dataset$TH)
dataset$type <- ifelse(dataset$TH > 0, "in", "out")
dataset$type <- factor(dataset$type, levels = c("out", "in"))
dataset$end <- cumsum(dataset$TH)
dataset$start <- c(0, head(dataset$end, -1))
Hover_Text <- paste(dataset$Category, "= ", dataset$TH, "<br>")
dataset$colors <- ifelse(dataset$type =="out","red","green")
g <- plot_ly(dataset, x = ~SortedCategory, y = ~start, type = 'bar', marker = list(color = 'rgba(1,1,1, 0.0)'), hoverinfo = 'text') %>%
add_trace(y = dataset$TH , marker = list(color = ~colors), hoverinfo = "text", text = Hover_Text ) %>%
layout(title = '',
xaxis = list(title = ""),
yaxis = list(title = ""),
barmode = 'stack',
margin = list(l = 50, r = 30, b = 50, t = 20),
showlegend = FALSE) %>%
add_annotations(text = dataset$TH,
x = dataset$SortedCategoryLabel,
y = dataset$end,
xref = "dataset$SortedCategoryLabel",
yref = "dataset$end",
font = list(family = 'Arial',
size = 14,
color = "black"),
showarrow = FALSE)
g
Attached the screenshot of the waterfall chart.
So for the first bar, I need the data marker to be just below the end of red bar. Currently it is overlapping with the bar. And similarly for others.
Any help would be really appreciated.
Regards,
Akash
You should specify valign and height inside add_annotations:
vert.align <- c("bottom","top")[as.numeric(dataset$TH>0)+1]
g <- plot_ly(dataset, x = ~SortedCategory, y = ~start, type = 'bar',
marker = list(color = 'rgba(1,1,1, 0.0)'), hoverinfo = 'text') %>%
add_trace(y = dataset$TH , marker = list(color = ~colors), hoverinfo = "text",
text = Hover_Text ) %>%
layout(title = '',
xaxis = list(title = ""),
yaxis = list(title = ""),
barmode = 'stack',
margin = list(l = 50, r = 30, b = 50, t = 20),
showlegend = FALSE) %>%
add_annotations(text = dataset$TH,
x = dataset$SortedCategoryLabel,
y = dataset$end,
xref = "x",
yref = "y",
valign=vert.align, height=40,
font = list(family = 'Arial',
size = 14,
color = "black"),
showarrow = FALSE)
g

Resources