Create a filled area line plot with annotated scatters using plotly - r

I want to create a filled area plot with line and scatters like in the screenshot attached but I do not know how could add scatters for every year of x-axis and also annotate its value. My code is:
library(plotly)
data <- t(USPersonalExpenditure)
data <- data.frame("year"=rownames(data), data)
fig <- plot_ly(data, x = ~year, y = ~Food.and.Tobacco, name = 'Food and Tobacco', type = 'scatter', mode = 'line', stackgroup = 'one', fillcolor = '#F5FF8D')
fig

The mode lines+markers+text allows you to define a line plot with markers and add some text.
I changed the type of year from factor to numeric, because I had to expand the xaxis for readabilty of the annotations.
library(plotly)
data <- t(USPersonalExpenditure)
data <- data.frame("year" = as.numeric(rownames(data)), data)
plot_ly(data,
x = ~year,
y = ~Food.and.Tobacco,
text = ~Food.and.Tobacco) %>%
add_trace(
type = 'scatter',
mode = 'lines+markers+text',
fill = 'tozeroy',
fillcolor = '#F5FF8D',
marker = list(color = 'black'),
line = list(color = 'black'),
textposition = "top center",
hovertemplate = paste0("<b>%{x}</b>
Cummulative Food and Tobacco: %{y}
<extra></extra>"),
hoveron = 'points') %>%
layout(xaxis = list(
range= list(min(data$year) - 1, max(data$year) + 1)))

Related

plotly stacked area graph custom colours from named vector

I am trying to use custom colours with a dataset in Plotly. The named vector works from a line graph and other graphs, but doesn't for the stacked area graph. Any ideas?
Also posted here: https://community.rstudio.com/t/plotly-stacked-area-graph-custom-colours-from-named-vector/153342
library(plotly)
library(tidyverse)
library(palmerpenguins) # for the dataset
penguins_cols <- c("Adelie" = "blue",
"Gentoo" = "red",
"Chinstrap" = "green")
# works for line graphs
plot_ly(penguins,
colors = penguins_cols) %>%
add_trace(x = ~bill_length_mm,
y = ~bill_depth_mm,
color = ~species,
type = "scatter",
mode = "lines+markers")
# doesn't work for area graphs
plot_ly(penguins,
colors = penguins_cols) %>%
add_trace(x = ~bill_length_mm,
y = ~bill_depth_mm,
fillcolor = ~species,
mode = "none",
stackgroup = 'one')
Perhaps there is more direct way but from the docs setting the colors via fillcolor seems to be the way to go, i.e. use fillcolor = ~penguins_cols[species] and set the names for the legend entries via name = ~species.
library(ggplot2)
library(plotly)
library(palmerpenguins)
penguins_cols <- c("Adelie" = "blue",
"Gentoo" = "red",
"Chinstrap" = "green")
plot_ly(penguins) %>%
add_trace(x = ~bill_length_mm,
y = ~bill_depth_mm,
name = ~species,
fillcolor = ~penguins_cols[species],
mode = "none",
type = "scatter",
stackgroup = 'one')
#> Warning: Ignoring 2 observations

R Plotly how to link text to bubbles in order to remove it when click on legend

With plotly on R, I have a bubble scatter plot and I want to add black text on each bubble. I also have my bubbles colored following a column of my data frame (Type: Yes or No). On my legend, when I click on "Yes" it will remove the bubbles linked to "Yes" but the text is staying, even if I added a 'legendgroup=~Type' in both traces.
How can I remove the text linked to the bubble when the user click on the legend ?
It is possible but only if I set 'color = ~Type' in my text trace, but I want to keep the text in black.
Example :
df <- data.frame(Projet=c("A", "B", "C"), x=c(0.2, 0.4, 0.6), y=c(0.6, 0.5, 0.1), Size=c(2,5,8), Type=c("Yes", "Yes", "No"))
fig <- plot_ly(df, x = ~ x, y = ~y) %>%
add_trace(color = ~Type, size = ~Size,
type = 'scatter', mode = 'markers',
sizes = c(20, 80),
marker = list(symbol = 'circle', sizemode = 'diameter',line = list(width = 2, color = 'gray60')),
hovertext = ~paste('Projet:', Projet, '<br>Size (kE):', Size),
hoverinfo="text", legendgroup=~Type) %>%
add_trace(type="scatter", mode="text", text=~Projet, showlegend=F, legendgroup=~Type)
fig
Which gives :
And if I click on "Yes" in the legend :
=> I want to remove the "A" and "B" text in this case
Thanks !
When I looked at your Plotly object, you assigned three group names to the parameter legendgroup. The reason it worked in your initial call add_trace is that Plotly will split a trace by color. In your call for text, everything is the same color, so it didn't automatically split the trace.
In your call for the text, you need to add split to split the trace.
Check it out
library(plotly)
df <- data.frame(Project = c("A", "B", "C"), x = c(0.2, 0.4, 0.6),
y = c(0.6, 0.5, 0.1), Size = c(2,5,8),
Type = c("Yes", "Yes", "No"))
fig <- plot_ly(df, x = ~ x, y = ~y) %>%
add_trace(color = ~Type, size = ~Size,
type = 'scatter', mode = 'markers',
sizes = c(20, 80),
marker = list(symbol = 'circle', sizemode = 'diameter',
line = list(width = 2, color = 'gray60')),
hovertext = ~paste('Project:', Project, '<br>Size (kE):', Size),
hoverinfo = "text", legendgroup = ~Type) %>%
add_trace(type = "scatter", mode = "text", text = ~Project,
showlegend = F, legendgroup = ~Type, split = ~Type) # <- I'm new!
fig

Plotly R setting the title of a continuous color legend

I'm trying to plot a 3D scatter using Plotly and R. Other than x, y and z I also would like to set the color of each point depending on a fourth variable.
I manage to set the plot correctly (the use of name = ~res is to show the value of res while hovering), but I am not able to change the name of the colorbar.
This is a mock code of what I've done:
library(tidyverse)
library(plotly)
a = seq(1,10,1)
b = seq(100,1000,100)
c = seq(1,4.9,0.4)
data = tibble(a,b,c)
data <- data %>% mutate(res = a+b+c)
layout_details <- list(xaxis = list(title = 'a [-]'),
yaxis = list(title = 'b [-]'),
zaxis = list(title = 'c [-]'),
coloraxis=list(colorbar=list(title=list(text='Here are the results'))))
p = plot_ly(data, x = ~a, y = ~b, z = ~c, color = ~res, type = 'scatter3d',
mode = 'markers', name = ~res, showlegend = FALSE, scene = 'scene1')
p <- p %>% layout(scene1 = layout_details)
p
I've noticed that a quite similar question was asked (R plotly to legend title value ignored for continuous color scatter plot), but without any answers.
Does anyone know how to solve this?
Thanks
You can define your colorbar inside the marker argument.
The name argument is interfering with the colorbar therefore I moved res from the name argument to the hovertemplate and the customdata.
Code
p = plot_ly(data, x = ~a, y = ~b, z = ~c,
name = "",
scene = 'scene1',
type = 'scatter3d',
mode = 'markers',
customdata = as.list(data$res),
hovertemplate = paste('x: %{x}',
'y: %{y}',
'z: %{z}',
'name: %{customdata}',
sep = "\n"),
marker = list(color = ~res,
colorbar = list(title = "Here are the results"),
colorscale='Viridis',
showscale = TRUE))
p <- p %>% layout(scene1 = layout_details)
p
Plot

Viewing hover info for overlapping scatter points in Plotly R

I was surpised I was not able to google this solution, so I thought i'd put up a post. Surely others have the same issue...
The issue I have is that when two or more scatter points overlap (i.e. same x and y), the hover information only shows the info of the top point.
Example:
df <- data.frame(ID=1:6, x=c(5:9, 7), y=c(1:5, 3)+10, info=paste('Hover information: ',c(LETTERS[c(1:6)])))
df
plot_ly(df) %>%
add_trace(x = ~x,
y = ~y,
type = 'scatter',
mode = 'markers',
marker = list(color = 1:6,
symbol = 1:6,
size = 25),
hoverinfo = "text",
text = df$info)
It is possible to make BOTH hoverinfo for the middle point to show up? Possibly as:
Hover information: C
Hover information: F
You can try to use add_markers() and jitter, e.g:
plot_ly(df) %>%
add_markers(x = ~jitter(x, 1),
y = ~jitter(y, 1),
type = 'scatter',
mode = 'markers',
marker = list(color = 1:6,
symbol = 1:6,
size = 25),
hoverinfo = "text",
text = ~info)
But to get multiple information as you designed, maybe you need to modify your dataframe (but you will lose the colour code):
df$info <- as.character(df$info)
df$combined_info[1] <- df$info[1]
for(i in 2:nrow(df)){
df$combined_info[i] <- df$info[i]
for(j in 2:i-1){
if((df$x[j] == df$x[i]) && (df$y[j] == df$y[i])){
df$combined_info[i] <- paste0(df$combined_info[j], "<br>",
df$info[i])
}
}
}
And then you can use the original plotly code, while changing the "text" argument:
plot_ly(df) %>%
add_trace(x = ~x,
...
text = ~combined_info)

Plotly zerolines at different levels on double axis plot

I'm trying to overlay a line chart and bar chart in plotly (with a vertical line designating an important date) and I'm encountering this issue where the two zero lines are offset instead of on the same line. I've tried messing around with the overlaying = 'y' option within layout and tried changing the order of the three trace components but nothing seems to help. Any ideas how to fix? Below is my code with dummy data:
(Also, bonus points if you can fix my legend-overlapping-y2axis issue)
date <- seq(as.Date("2015/6/1"), by = "month", length.out = 19)
wires_mnth <- c(rep(0,8),100000,750000,1200000,2500000,3100000,5500000,7500000,8000000,9900000,11300000,11000000)
wires_cnt <- c(rep(0,8),100,200,250,325,475,600,750,800,1000,1150,1200)
data <- data.frame(date, wires_mnth)
plot_ly(data) %>%
add_trace(x = ~date, y = ~wires_cnt, type = 'bar', name = 'Wires Count',
yaxis = 'y2', opacity = .5) %>%
add_trace(x = ~date, y = ~wires_mnth, type = 'scatter', mode = 'lines', name
= 'Monthly Wires') %>%
add_trace(x = c(2016,2016), y = c(0, 12000000), type = 'scatter', mode =
"lines", name = 'Sanctions Removed') %>%
layout(title = 'Monthly Aggregate Wire Transfers to Iran',
xaxis = list(title = ''),
yaxis = list(side = 'left', title = 'Wire Amounts (USD)', showgrid =
FALSE, zeroline = FALSE),
yaxis2 = list(side = 'right', overlaying = 'y', title = 'Wires Count',
showgrid = FALSE, zeroline = FALSE)
)
You could add rangemode='nonnegative' to your layout or specify the range manually via range=list(0, max(wires_mnth).
For your bonus question, you can set the x-position of the legend, e.g.
legend = list(x = 1.2)

Resources