Plotly subplots with shared legend in R - r

I have made twoplots using plotly, which are working fine individually, but when combined using subplot I can't seem to figure out how to combine the legends. I have tried to use showlegend = F in plot_ly in one of the plots, but this just removes it completely - what I want is to control both subplots with the same legend.
My code is as follows:
coronavirus_not_china <- coronavirus %>%
filter(!(country == "China"))
cases_not_china_plot <- coronavirus_not_china %>%
group_by(type, date) %>%
summarise(total_cases = sum(cases)) %>%
pivot_wider(names_from = type, values_from = total_cases) %>%
arrange(date) %>%
mutate(active = confirmed - death - recovered) %>%
mutate(active_total = cumsum(active),
recovered_total = cumsum(recovered),
death_total = cumsum(death)) %>%
plot_ly(x = ~ date,
y = ~ active_total,
name = 'Active',
fillcolor = '#1f77b4',
type = 'scatter',
mode = 'none',
stackgroup = 'one',
showlegend = F) %>%
add_trace(y = ~ death_total,
name = "Death",
fillcolor = '#E41317') %>%
add_trace(y = ~recovered_total,
name = 'Recovered',
fillcolor = 'forestgreen') %>%
layout(title = "Distribution of Covid19 Cases outside China",
legend = list(x = 0.1, y = 0.9),
yaxis = list(title = "Number of Cases", showgrid = T))
coronavirus_china <- coronavirus %>%
filter((country == "China"))
cases_china_plot <- coronavirus_china %>%
group_by(type, date) %>%
summarise(total_cases = sum(cases)) %>%
pivot_wider(names_from = type, values_from = total_cases) %>%
arrange(date) %>%
mutate(active = confirmed - death - recovered) %>%
mutate(active_total = cumsum(active),
recovered_total = cumsum(recovered),
death_total = cumsum(death)) %>%
plot_ly(x = ~ date,
y = ~ active_total,
name = 'Active',
fillcolor = '#1f77b4',
type = 'scatter',
mode = 'none',
stackgroup = 'one',
showlegend = T) %>%
add_trace(y = ~ death_total,
name = "Death",
fillcolor = '#E41317') %>%
add_trace(y = ~recovered_total,
name = 'Recovered',
fillcolor = 'forestgreen') %>%
layout(title = "Distribution of Covid19 Cases inside China",
legend = list(x = 0.1, y = 0.9),
yaxis = list(title = "Number of Cases", showgrid = F))
And I create the subplots as:
subplot(cases_not_china_plot, cases_china_plot, nrows = 2, margin = 0.05, shareX = T) %>%
layout(title="Coronavirus cases outside China and in China", ylab("Number of cases"))
I am quite new to R, so if there is a smarter way to do what I desire, please let me know.
With the above code, my output is:

Related

Adding Images to animations in plotly (R)

I am trying to create an animation where an image has to move together with the dot that you can see in this image:
I have a dataset about Formula 1 and I want to show the image of the car instead of the dot in the image.
Here you have a summary of my dataset:
And the code of the graph:
prep = data[data$year == 2021,] %>% split(.$date) %>% accumulate(., ~bind_rows(.x,.y))%>%
bind_rows(.id = "frame")
prep2 = data[data$year == 2021,] %>% split(.$date) %>%
bind_rows(.id = "frame")
prep%>%
plot_ly(x = ~name, y = ~points, color = ~factor(name)) %>%
add_lines(frame = ~as.Date(frame, format = '%Y-%m-%d'))%>%
add_markers(data = prep2, frame = ~as.Date(frame, format = '%Y-%m-%d'))%>%
layout(yaxis = list(title = 'Puntos'),showlegend = FALSE,xaxis = list(title = 'Fecha de la carrera',range = c(as.Date(min(data$date[data$year == 2021]), format="%d/%m/%Y"),as.Date(max(data$date[data$year == 2021]), format="%d/%m/%Y"))))%>%
animation_slider(currentvalue = list(prefix = "Carrera "))

Add country polygons to mapbox

I want to recreate a choropleth map with country polygons like the county level choropleth map here. And here is its result.
I try to repeat the same procedure for a world map
library(ggplot2)
library(dplyr)
library(maps)
WorldData <- map_data('world') %>% filter(region != "Antarctica") %>% fortify
Country<-c("United States","Canada","France","Italy","Turkey","United States","Canada","France","Italy","Turkey")
Val<-c(50,67,89,567,9,50,67,89,567,9)
Name<-c('AD',"FGH","BGH","FGFG","EWRW",'ADy',"FGyH","BGyH","FGFyG","EyWRW")
Test<-data.frame(Country,Val,Name)
V1 <- aggregate(Val~Country,Test,sum)
colnames(WorldData)[5]<-"Country"
m2 <- data.frame(merge(V1,WorldData , by=c("Country"), all.x=T))
p <- m2 %>%
group_by(group) %>%
plot_mapbox(x = ~long, y = ~lat, color = ~Val1, colors = c('#ffeda0','#f03b20'),
text = ~Country, hoverinfo = 'text', showlegend = FALSE) %>%
add_polygons(
line = list(width = 0.4)
) %>%
add_polygons(fillcolor = ~Val1,
line = list(color = 'black', width = 0.5),
showlegend = FALSE, hoverinfo = 'none'
) %>%
layout(
xaxis = list(title = "", showgrid = FALSE, showticklabels = FALSE),
yaxis = list(title = "", showgrid = FALSE, showticklabels = FALSE),
mapbox = list(
style = 'light',
zoom = 4,
center = list(lat = ~median(lat), lon = ~median(long))),
margin = list(l = 0, r = 0, b = 0, t = 0, pad = 0)
)
p
but I get:
I think you just need to order your data per the 'order' column in your data:
p <- m2 %>%
arrange(order) %>%
group_by(group) %>%
...
...
That worked for me.

Bar with negative stack and positive labels

I'm trying to make in R (Shiny) a reversed stacked bar highchart. I already found how to make the graph, but I can't find out how to make the labels on the x-axis positive, like here: https://www.highcharts.com/demo/bar-negative-stack
I've tried to apply the abs() function, but it didn't work so far. Does anyone have a solution?
highchart() %>%
hc_chart(type = "bar") %>%
hc_title(text = "Example") %>%
hc_yAxis(title = list(text = ""), labels = list(format = "{value}")) %>%
hc_plotOptions(series=list(stacking='normal'),
column = list( dataLabels = list(enabled = FALSE),
enableMouseTracking = TRUE)) %>%
hc_legend(enabled = FALSE) %>%
hc_xAxis(reversed=FALSE, opposite=TRUE, reversed=FALSE) %>%
hc_add_series(name="neutral", id='neutral', color=c("#766A62"), data=list(2, 8)) %>%
hc_add_series(name="Neutral",linkedTo='neutral',color=c("#ffeeff"),data=list(-5, -3))
I want the values of the bars and the labels on the x-axis all to be positive. Any ideas welcome.
Using your code:
highchart() %>%
hc_chart(type = "bar") %>%
hc_title(text = "Example") %>%
hc_yAxis(title = list(text = ""),labels = list(format = "{value}")) %>%
hc_plotOptions(series=list(stacking='normal'),column = list( dataLabels = list(enabled = FALSE),
enableMouseTracking = TRUE)) %>%
hc_legend(enabled = FALSE) %>%
hc_xAxis(list(categories = c("0-4", "5-9"),
reversed=FALSE ),
list(reversed=FALSE,opposite=TRUE,
reversed=FALSE,
categories =c("0-4", "5-9"),
linkedTo = 0)) %>%
hc_yAxis(
labels = list(
formatter = JS("function(){ return Math.abs(this.value) + '%'; }"))) %>%
hc_add_series(name="neutral",id='neutral',color=c("#766A62"),data=list(2, 8)) %>%
hc_add_series(name="Neutral",linkedTo='neutral',color=c("#ffeeff"),data=list(-5, -3))
Following lines are modified:
hc_xAxis(list(categories = c("0-4", "5-9"),
reversed=FALSE ),
list(reversed=FALSE,opposite=TRUE,
reversed=FALSE,
categories =c("0-4", "5-9"),
linkedTo = 0)) %>%
hc_yAxis(
labels = list(
formatter = JS("function(){ return Math.abs(this.value) + '%'; }")))
Result:

R plotly: Stacked Area Chart with Cumulative Values not stacking properly

I've got three columns of data I would like to plot as a cumulative stacked area chart over a 10 day sampling period.
ID variable value
dallas sample.01 0.0012
austin sample.01 0.23
seattle sample.01 0.01
I'd like it to look something like this:
But it's coming out like this:
What am I doing wrong with my code?
melted_dat %>%
group_by(value,ID) %>%
plot_ly(
x = ~variable,
y = ~value,
color = ~ID,
type='scatter',
mode = 'none',
fill = 'tonexty',
stackgroup = 'one',
fillcolor = ~ID) %>%
layout(showlegend = FALSE)
I think you need to add the groups trace by trace. As in the following example (from here):
library(plotly)
data <- t(USPersonalExpenditure)
data <- data.frame("year"=rownames(data), data)
p <- plot_ly(data, x = ~year, y = ~Food.and.Tobacco, name = 'Food and Tobacco', type = 'scatter', mode = 'none', stackgroup = 'one', groupnorm = 'percent', fillcolor = '#F5FF8D') %>%
add_trace(y = ~Household.Operation, name = 'Household Operation', fillcolor = '#50CB86') %>%
add_trace(y = ~Medical.and.Health, name = 'Medical and Health', fillcolor = '#4C74C9') %>%
add_trace(y = ~Personal.Care, name = 'Personal Care', fillcolor = '#700961') %>%
add_trace(y = ~Private.Education, name = 'Private Education', fillcolor = '#312F44') %>%
layout(title = 'United States Personal Expenditures by Categories',
xaxis = list(title = "",
showgrid = FALSE),
yaxis = list(title = "Proportion from the Total Expenditures",
showgrid = FALSE,
ticksuffix = '%'))
# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = api_create(p, filename="area-stackedcum")
chart_link
If you are following the cumulative example from plotly, don't do the group_by .... cumsum, I also get rid of fillcolor

Add reference line for each bar in bar chart using highcharter

I want to put a specific line for each bar likes the following:
But, I can't. To do this, I have tried the following code to put a particular text at least, but it does not work anymore:
mydata <- data.frame(A=runif(1:10),
B=runif(1:10),
C=runif(1:10))
highchart() %>%
hc_chart(type = "column", inverted = TRUE) %>%
hc_title(text = "MyGraph") %>%
hc_yAxis(title = list(text = "Weights")) %>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal",
enableMouseTracking = FALSE)
) %>%
hc_legend(layout="vertical") %>%
hc_tooltip(formatter = function(){ return("<b> test</b><br/>")},
useHtml = TRUE) %>%
hc_series(list(name="A",data=mydata$A),
list(name="B",data=mydata$B),
list(name="C",data=mydata$C))
My question is how can I add red lines into the bar chart for each bar line?
Here is a possible solution:
set.seed(1)
mydata <- data.frame(A=runif(1:10), B=runif(1:10), C=runif(1:10))
library(highcharter)
hc <- highchart() %>%
hc_chart(type = "column", inverted = TRUE) %>%
hc_title(text = "MyGraph") %>%
hc_yAxis(title = list(text = "Weights")) %>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal", groupPadding=0,
enableMouseTracking = FALSE)
) %>%
hc_legend(layout="vertical") %>%
hc_tooltip(formatter = function(){ return("<b> test</b><br/>")},
useHtml = TRUE) %>%
hc_series(list(name="A",data=mydata$A),
list(name="B",data=mydata$B),
list(name="C",data=mydata$C))
# x position of red lines
linepos <- c(1.3, 0.7, 1.8, 1.2, 1.0, 1.6, 0.7, 1.7, 0.8, 1.1)
# height of red lines
lw <- 0.35
for (k in 1:length(linepos)) {
df <- data.frame(x=c(k-1-lw,k-1+lw),y=rep(linepos[k],2))
hc <- hc %>%
hc_add_series(data = df, type = 'line', marker=list(enabled=FALSE),
x = ~x, y= ~y, color='red', lineWidth=5, showInLegend=FALSE,
enableMouseTracking = FALSE)
}
hc

Resources