R plot_ly: How to add horizontal space in plot area? - r

I am using plot_ly in R to create a line chart. By default, the line runs right up to the left and right edges of the plot area. I would like to add some space here, as is done by default in ggplot. Does anyone know how to do this with plot_ly?
Reproducible example:
df <- data.frame(date = seq(as.Date('2021-01-01'), length=50, by='day'),
value = rnorm(50))
plot_ly(df, x=~date, y=~value) %>%
add_lines(color=I('black')) %>%
layout(title = 'plot_ly', plot_bgcolor = 'E9E9E9')
ggplot(df, aes(x=date, y=value)) +
geom_line() +
ggtitle('ggplot')
I would like to add the space shown below with red arrows:

You can set the range in xaxis :
library(plotly)
plot_ly(df, x=~date, y=~value) %>%
add_lines(color=I('black')) %>%
layout(title = 'plot_ly', plot_bgcolor = 'E9E9E9',
xaxis = list(range = c(min(df$date) - 3, max(df$date) + 3)))

Related

Placing Spaces Between the Titles of Plots

I made this pie chart in R:
# https://plotly.com/r/text-and-annotations/
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv", stringsAsFactors = FALSE)
df <- df[which(df$year==2007 & df$continent=='Asia'),]
fig <- plot_ly(df, type='pie', labels = ~country, values = ~pop, textposition = 'inside')
fig1 <- fig %>% layout(uniformtext=list(minsize=12, mode='hide'))
fig1 <- fig1 %>% add_annotations(
y=1.05,
x=0.5,
text="Countries of the World",
showarrow=F,
font=list(size=15)
)
Everything works fine here, but I notice that when I am working with my real data, the title of the pie chart and the actual pie chart always come very close to intersecting with each other - I would like to try and change this.
I was thinking if there might be a way to avoid this problem. I thought that perhaps I could add more space between the title and the actual pie chart to avoid this problem from happening. I found this post here (how to adjust title space and plot plotly in r) and tried to apply the advice that was suggested in the answer:
mrg <- list(l = 50, r = 50,
b = 50, t = 50,
pad = 20)
fig1 %>% layout(margin = mrg)
However, this has not seemed to add any space between the pie chart and the title of the pie chart.
Can someone please show me how to do this correctly?
Thank you!
Here is one option making use of layout for the title and adjusting the spacing. Then, you can just adjust the margins to get the desired spacing.
library(plotly)
plot_ly(df, type='pie', labels = ~country, values = ~pop, textposition = 'inside') %>%
layout(uniformtext=list(minsize=12, mode='hide')) %>%
layout(title = list(text = 'Countries of the World',
y=1.25,
x=0.43, font=list(size = 30)),
autosize = T,
margin=list( l = 50, r = 50, b = 100, t = 100, pad = 4))
Output

Vertical line appearing when manually adjust x-axis range using plotly

I am creating a chart using plotly and would like to extend the x-axis to 0. However, for some reason, when I do this, plotly renders a vertical reference line at 0, as shown below. Is there a way to omit this line and have the vertical line at 0 simply appear gray line the other grid lines?
library(dplyr)
library(plotly)
mtcars %>%
mutate(cyl = factor(cyl)) %>%
plot_ly(
x = ~mpg,
y = ~cyl,
type = "scatter",
mode = "markers"
) %>%
layout(xaxis = list(
range = c(0, 35)
))
By default plotly will automatically draw a zeroline. That could be toggled on and off via layout argument zeroline. If you want a zeroline you could set the color to be equal to the color of the gridlines via zerolinecolor="#eee", where #eee is the default grid line color. See the docs.
library(dplyr)
library(plotly)
mtcars %>%
mutate(cyl = factor(cyl)) %>%
plot_ly(
x = ~mpg,
y = ~cyl,
type = "scatter",
mode = "markers"
) %>%
layout(xaxis = list(
range = c(0, 35),
zeroline = FALSE
#zerolinecolor = "#eee"
))

Plotly R: Interaction between subplot legend and highlight select

I am trying to get another plot to react to both legend (select/deselect levels of a factor) and drag select. In the following toy example drag select works as intended: the violin and boxplot are re-rendered to depict the points that are selected using the mouse. The legend works for the scatterplot, but not for the boxplot and violin that don't seem to share the legend. I read many posts about shared legend, but nothing worked for subplots of different types.
Even more surprisingly, when deplying to plotly cloud, the plot also loses it's drag select feature (altough I don't need the plotly cloud, I thought I should mention this).
Just to be clear, I'd like the boxplot and violin to be re-rendered based both on selecting on legend and drag-select on scatterplot. As these features theoretically work, the legend should provide the full data or subsets based on levels of the factor used for legend from which the drag selection could be carried out afterwards.
library(plotly)
d <- mtcars
d$cyl <- as.factor(d$cyl)
d <- highlight_key(mtcars)
sp <- plot_ly(d, x = ~mpg, y = ~disp,
color = ~factor(cyl), colors = c("red", "green", "blue"),
legendgroup = ~factor(cyl), showlegend = T) %>%
add_markers()
box <-
plot_ly(d, y = ~disp,
color = I("black"),
legendgroup = ~factor(cyl), showlegend = F) %>%
add_boxplot(name = " ")
violin <-
plot_ly(d, y = ~disp,
color = I("black"),
legendgroup = ~factor(cyl), showlegend = F) %>%
add_trace(type = "violin", name = " ")
p <-
subplot(sp, box, violin, shareY = TRUE, titleX = TRUE, titleY = TRUE) %>%
layout(
dragmode = "select",
barmode = "overlay",
title = "Click and drag scatterplot",
showlegend = TRUE
) %>%
highlight(on = "plotly_selected", off = "plotly_deselect")
p
Any help is greatly appreciated.

Add a line to a boxplot using plotly

Is it possible to add vertical line to a boxplot in plotly? I know it works in ggplot2, but I need it in plotly. Would be nice if I don't need to convert my static ggplot every time.
Here is a minimal example
plot_ly(x = ~rnorm(50), type = "box") %>%
add_trace(x = ~c(0.75),y=c(-2,0.5),type='scatter',mode='lines')
Instead of the line stoping before I want the line to go through the boxplot. In addition I want the same plot extent as the single boxplot.
Change the sequence of calls:
library(plotly)
plot_ly(x = ~c(0.75), y=c(-2,2), type='scatter', mode='lines') %>%
add_boxplot(x = ~rnorm(50), inherit = F) %>%
layout(yaxis = list(range = c(-2, 2)))

Plotly markers to appear in a bar chart

I am new to plotly and want to make my own bullet chart (a bit like http://bl.ocks.org/mbostock/4061961) that has markers/traces to show the values of the relevant values when comparing actual vs expected.
Below is my attempt:
q <- ggplot(data.frame(measure='',actual=25),aes(x=measure,y=actual))+
geom_bar(stat='identity')+
ylim(c(0,35))+
geom_hline(yintercept = 30,color='red')+
geom_text(y=30,label='Expected',angle=270,vjust=0)+
coord_flip()+
ylab('Num. of carrots')
q
q1 <- ggplotly(q) %>% add_markers()
q1
When converting it to plotly using ggplotly, the text looks like it has not rotated correctly, and the markers/traces do not show for the bar chart...Any help here would be much appreciated.
Kindest regards,
HLM
I do not think that plotly supports rotating text for type="scatter" (which is how ggplotly is interpreting your geom_text). You can delete the geom_text line from the ggplot graph, then add text to the plotly one using annotations:
q1 <- ggplotly(q) %>% add_markers() %>%
layout(annotations = list(x = 30, y = 1, text = "Expected", textangle=270))
q1
update
The 2nd part of your question (how to also get hover info on the bar) is slightly trickier. To get the hover info, we can create the bars using the plotly API directly like this
p.bars = plot_ly(data = data.frame(measure='', actual=25)) %>%
add_bars(y=~measure, x=~actual, orientation="h")
we can add the text annotation to it like this
p.bars.text = p.bars %>%
layout(annotations = list(x = 30, y = 0, text = "Expected", textangle=270,
showarrow=F, xanchor="center"))
But the problem is that adding a line also to this plot by
p.bars.text %>% add_segments(x=30, xend=30, y=-0.5, yend=0.5)
gives an error
Error in populate_categorical_axes(p) : Can't display both discrete & non-discrete data on same axis
I.e. we can only specify the y values of the line with respect to categorical values of y. So, for example we can do
dat1 = data.frame(measure=letters[1:2], actual=c(25,20))
plot_ly(data = dat1) %>%
add_bars(y=~measure, x=~actual, orientation="h") %>%
layout(annotations = list(x = 29, y = 0, text = "Expected", textangle=270,
showarrow=F, xanchor="center")) %>%
add_segments(x=30, xend=30, y='a', yend='b')
which gives the following in which the line is aligned with the category labels rather than with the width of the bars
The only solution I have to this at the moment is to use a numeric axis for the categories, and then set the axis labels using ticktext:
plot_ly(data = data.frame(measure=c(0,1), actual=c(25,20))) %>%
add_bars(y=~measure, x=~actual, orientation="h", showlegend=F) %>%
add_segments(x=30, xend=30, y=-0.4, yend=0.4, showlegend=F) %>%
layout(annotations = list(x = 29.5, y = 0, text = "Expected", textangle=270, showarrow=F, xanchor="center"),
yaxis = list(tickmode="array", tickvals=c(0,1), ticktext=c("", "") ))

Resources