How to plot horizontal lines between y-axis ticks in plotly? - r

Here is some example code to illustrate my issue.
library(plotly)
p <- plot_ly(x = mtcars$mpg, y = seq_along(rownames(mtcars)), text=rownames(mtcars),
type = 'scatter', mode = 'markers')
ax <- list(
title = "",
ticktext = rownames(mtcars),
tickvals = seq(1,32)
)
line <- list(
type = "line",
line = list(color = "pink"),
xref = "x",
yref = "y"
layer = 'below'
)
lines <- list()
for (i in seq_along(rownames(mtcars))) {
line[["x0"]] <- mtcars$mpg[i] - 1
line[["x1"]] <- mtcars$mpg[i] + 1
line[c("y0", "y1")] <- i
lines <- c(lines, list(line))
}
p <- layout(p, title = 'Highlighting with Lines', shapes = lines, yaxis=ax)
p
I would like to add horizontal lines through the plot to separate each y-axis label. I would prefer the line split the labels as well as the graph, but splitting just the graph would suffice. I have looked extensively through the plotly reference but have yet to find anything that appears to help. I was told that there might be some sort of solution through some custom JS in the y-axisof the layout section, but am unsure on how I would go about this / am not very JS savvy.

I was able to accomplish this by adding more lines to the lines list. Under the for loop shown above, if you add the code:
for (i in seq_along(rownames(mtcars))) {
line[["x0"]] <- 10
line[["x1"]] <- 35
line[c("y0", "y1")] <- i-.5
lines <- c(lines, list(line))
}
It will place a separating line in between each of the data lines.

Related

subplot hides titles and x and y lables of plots on the shiny

I have some plots to show on the shiny app.
I used Plotly to show them. please look at a part of my code.
As you can see I added the title and x-axis and y-axis labels for each of the plots. But when I merge them by "subplot", it hides the labels. I need to show all plots at the same time on a page.
How can I resolve it?
#UI section
plotlyOutput("fancyPlot")
#Server side
output$fancyPlot <- renderPlotly({
# I got E somehow, its my dataset
#I didnt write the lines which I got the other vectors and variables like group1_vectors
for (i in 1: length(s)){
plot1 = ggplot(E, aes(x = group1 , y = group2)) +
labs(title= gene_vectors[i],
x= group1_vectors[i], y = group2_vectors[i])+
geom_point(color='tomato')
plot_list_final[[i]] = plot1
}
plot_list_final = do.call(tagList, plot_list_final)
f = length(s)
p_last <- subplot(plot_list_final[1:f], nrows = f, margin = 0.045) %>%
layout(title = "Plots of selected TFs")
# p_last = p_last + coord_fixed(ratio = 1, xlim = NULL, ylim = NULL, expand = TRUE, clip = "on")
dev.off()
return(p_last)
})

Writing the symbol degrees celsius in axis titles with R/plotly

I'm trying to write the symbol degrees celsius with R/Plotly in one of my titles. It works when I just use a simple plot a below:
# Working code
library(latex2exp)
set.seed(1)
betas <- rnorm(1000)
hist(betas, main = TeX("Temperature (^0C)"))
However, when I try to run the code through plotly, I get the following error: "unimplemented type 'expression' in 'HashTableSetup'".
#Initialise the plot
p <- plot_ly()
#Add axis names
#Font
f <- list(
family = "Courier New, monospace",
size = 18,
color = "#7f7f7f")
#X axis name
x <- list(
title = "x Axis",
titlefont = f)
#Y Axis name
y <- list(
title = TeX("Temperature (^0C)"),
titlefont = f)
#Add layout
p <- p %>%
layout(xaxis = x, yaxis= y)
p
Any ideas?
Try,
title = "Temperature (\u00B0C)"
Try title = expression("Temperature ("*~degree*C*")") or title = "Temperature (°C)"
I just found a hacky solution: Look for the special character on google and copy and paste it directly in the R code.
#Y Axis name
y <- list(
title = "Temperature (°C)",
titlefont = f)
I'm still interested in a less hacky solution which allows to insert LaTeX into Plotly.

How to plot horizontal lines through markers in plotly?

Here is some example code I wrote to illustrate my problem. Right now, the plot generates only the points. What I want to do is have horizontal lines that go through each point, spanning a length of 1 to each side. (i.e. for a point at (2,1) I want the line to run from (1,1) to (3,1)) How can I do this in plotly? I've looked here but can't seem to figure out how to get this to work when the y-axis is not numerical.
library(plotly)
p <- plot_ly(data = mtcars, x = ~mtcars$mpg, y = rownames(mtcars), type = 'scatter', mode = 'markers')
p
EDIT is the output from the code provided in the accepted answer (except showing all car names). I was wondering if there is a way to draw a horizontal line between each y-axis label, so that for example, between "Volvo 142E" and "Maserati Bora", a line separates them, and goes for the length of the plot. Right now, each horizontal line of the plot has a point on it. I want to separate each of those lines with another line.
To get this to work we had to replot the original scatter plot with an using the row index to prevent plotly from reordering cars. Then I added back to the axis labels.
library(plotly)
##I added the text argument(hover over text) so that I could make sure
##that the yaxis labels matched the points. feel free to delete.
p <- plot_ly(x = mtcars$mpg, y = seq_along(rownames(mtcars)), text=rownames(mtcars),
type = 'scatter', mode = 'markers')
##This sets some attributes for the yaxis. Note: in your origianl plot every other
##car name was shown on the y-axis so that is what I recreated but you could remove
##the "seq(1,32, by=2)" to show all car names.
ax <- list(
title = "",
ticktext = rownames(mtcars)[seq(1,32, by=2)],
tickvals = seq(1,32, by=2)
)
##This is taken from the plotly help page. y0 and y1 now are set to equal the row
##number and x0 and x1 are +/-1 from the car's mpg
line <- list(
type = "line",
line = list(color = "pink"),
xref = "x",
yref = "y"
)
lines <- list()
for (i in seq_along(rownames(mtcars))) {
line[["x0"]] <- mtcars$mpg[i] - 1
line[["x1"]] <- mtcars$mpg[i] + 1
line[c("y0", "y1")] <- i
lines <- c(lines, list(line))
}
p <- layout(p, title = 'Highlighting with Lines', shapes = lines, yaxis=ax)
p
Update based on OP's request.
To underline text in plotly use HTML tags. But <u> </u> does not work so we have to use <span> </span>...
ax2 <- list(
title = "", ticktext = paste0('<span style="text-decoration: underline;">',
rownames(mtcars)[1:32 %% 2 ==0],"</span>"),
tickvals = seq(1,32, by=2), style=list(textDecoration="underline"))

Manipulating R plotly legend

Probably an easy question:
Trying to use plotly to produce a scatter plot and customize the legend.
Here's my data:
require(plotly)
set.seed(1)
my.df <- data.frame(id=LETTERS[sample(26,100,replace=T)],x=rnorm(100),y=rnorm(100),sig=runif(100,0,1),stringsAsFactors = F)
In my case I'm calling this with the column indices, thus:
x.idx <- which(colnames(my.df) == "x")
y.idx <- which(colnames(my.df) == "y")
sig.idx <- which(colnames(my.df) == "sig")
sig.name <- "p-value"
And what I want to do is have the legend title be sig.name and make the legend smaller than the default size. So I'm trying:
p <- plot_ly(x=~my.df[,x.idx],y=~my.df[,y.idx],color=~my.df[,sig.idx],text=~my.df$id,colors=c("darkblue","darkred")) %>% add_annotations(text=sig.name,xref="paper",yref="paper",xanchor="left",x=1,y=1,yanchor="top",legendtitle=T,showarrow=FALSE) %>% layout(legend=list(y=0.8,yanchor="top"),xaxis=list(title=colnames(my.df)[x.idx],zeroline=F),yaxis=list(title=colnames(my.df)[y.idx],zeroline=F))
Which gives me:
Not exactly what I want.
So:
How do I delete the default legend title?
How do I make the legend smaller?
You are probably looking for colorbar: len and colorbar: title.
plot_ly(type = 'scatter',
mode = 'markers',
x = ~my.df[,x.idx],
y = ~my.df[,y.idx],
color = ~my.df[,sig.idx],
text =~my.df$id,
colors = c("darkblue","darkred"),
marker = list(colorbar = list(len = 0.2,
title = sig.name)
)
)

common axis subplots with plot.ly for R

I am attempting to use subplots with the plot.ly R library for interactive online charting. I can successfully create a subplot, however am struggling to only have a single y-axis that is common to both charts.
The plot.ly website does provide an example for a common x-axis, however this is done slightly differently using and additional trace rather than the group option that is provided within the plot_ly() function.
example code:
library(data.table)
library(plotly)
dt <- data.table(x = c("A","B","C","D","A","B","C","D"),
y = c(12,4,3,9,5,10,3,7),
group = factor(c(rep("G1",4),rep("G2",4))))
dt$id <- as.integer(dt$group)
xx <- xaxis_standard
yy <- yaxis_standard
p <- plot_ly(dt, x=x, y=y, group = group, xaxis = paste0("x",id))
p <- layout(p, yaxis = list(range = c(0, max(y))))
p <- subplot(p, margin = 0.05)
p <- layout(p,showlegend = F, yaxis = list(anchor = 'x1'))
p
This image shows what results when I execute the code.
What I would like to have is the same chart, however without the y-axis on the right hand subplot.
Subplots are on separate axes labeled xaxis2, yaxis2, etc. Those axes are also arguments to layout().
p <- layout(p, showlegend = F, yaxis = list(anchor = 'x1'),
yaxis2 = list(showticklabels = F))
p

Resources