R programming Plotly bar chart grouped bars with multiple y axis - r

I am trying to do a grouped bar chart with two different Y axis for measure two different columns. Here is the data:
SUCURSAL EXISTENCIA COSTO_MEDIO
0 MELENARA 0.128 643.2
1 LAS TORRES 1.872 659.2
2 GALDAR 0.304 659.2
3 SEBADAL 0.851 623.8
4 ARINAGA 0.176 620.4
5 LANZAROTE 0.232 686.4
6 FUERTEVENTURA 0.480 680.2
and here is my code:
ay <- list(
tickfont = list(color = "red"),
overlaying = "y1",
side = "right"
)
p <- plot_ly(dfplot, x = dfplot$SUCURSAL, y = dfplot$EXISTENCIA, type = "bar", opacity = 0.4, name = 'EXISTENCIA', yaxis = "y1") %>%
add_trace(x = dfplot$SUCURSAL, y = dfplot$COSTO_MEDIO, type = "bar", name = 'COSTO', yaxis = "y2") %>%
layout( xaxis = list(title = ""), yaxis = list(title = "", tickfont= list(size = 10, color = "black"), showticklabels = TRUE), yaxis2= ay, barmode = 'group' ) %>%
config(displayModeBar = F)
p
The problem I have is that the two groups of bars are overlayed. It is impossible for me to see it grouped, aside each other. How can I represent it with the two groups of bars?
Any idea?

Related

Create a stacked bar chart with 3 traces for 2 bars

I am trying to replicate the following stacked bar chart with plotly. I attach one screenshot for every hover text I get when hovering on a bar. As you will see there are 2 issues. First I cannot achieve 3 colors, besides the fact that I create them in the legend and secondly I cannot put First dose as top bar besides the fact that I use factor() based on the levels. Maybe there is an issue with the way I have created my dataset. I have no problem if you have to reform it instead of fix the plotly code to replicate the chart.
library(plotly)
Category<-c("First dose","Full vaccination")
`Uptake first dose`<-c(19.8,7.6)
`Uptake full vaccination`<-c(0,0)
`Not vaccinated`<-c(80.2,92.4)
ch5<-data.frame(Category,`Uptake first dose`,`Uptake full vaccination`,`Not vaccinated`)
ch5$Category <- factor(ch5$Category, levels = ch5[["Category"]])
ax <- list(
title = "",
showticklabels = FALSE,
showgrid = FALSE
)
fig <- plot_ly(ch5, y = ~Category, x = ~`Uptake first dose`,
type = 'bar', name = 'Uptake first dose',marker = list(color = 'lightgreen'))
fig <- fig %>% add_trace(x = ~`Uptake full vaccination`, name = 'Uptake full vaccination',marker = list(color = 'green'))
fig <- fig %>% add_trace(x = ~`Not vaccinated`, name = 'Not vaccinated',marker = list(color = 'gray'))
fig <- fig %>% layout(yaxis = ax,xaxis=list(title="",showgrid=F), barmode = 'stack')
fig
There might be a problem with your dataset. The 7.6% of full vaccination is listed under first doese. Therefore your coloring might not work.
Furthermore I transformed the data into a long format for an easy way to create hovertemplates.
library(plotly)
library(tidyverse)
# data
Category<-c("First dose","Full vaccination")
`Uptake first dose`<-c(19.8,0)
`Uptake full vaccination`<-c(0,7.6)
`Not vaccinated`<-c(80.2,92.4)
ch5<-data.frame(Category,`Uptake first dose`,`Uptake full vaccination`,`Not vaccinated`)
# transform data
data.long <- ch5 %>%
pivot_longer(cols = -Category,
names_to = "vac",
values_to = "percent") %>%
mutate(vac = str_replace_all(vac, "\\.", " "),
vac = fct_rev(factor(vac)))
# add plot
plot_ly(data.long) %>%
add_bars(y = ~Category,
x = ~percent,
color = ~vac,
text = ~vac,
colors = c("darkgreen", "green", "gray"),
hovertemplate = paste('<b>%{y}</b>',
'<br>%{text}: %{x} ',
'<extra></extra>')) %>%
layout(barmode = "stack",
yaxis = list(autorange="reversed"),
hoverlabel = list(bgcolor = "black",
bordercolor = "black",
font = list(color = "white")),
shapes = list(type = "line",
y0 = 0, y1 = 1, yref = "paper",
x0 = 70, x1 = 70),
annotations = list(text = "Target (70.0%)",
showarrow = FALSE,
x = 70,
y = 1.05,
yref = "paper"))

Removing Unused Subplot in R Plotly

When using plotly (in R), after combining subplots there remains an unused and blank subplot. I've recreated the issue using the ggplot2 dataset mpg below.
library(dplyr)
library(ggplot2)
library(plotly)
audi <- mpg %>%
filter(manufacturer == "audi")
chevy <- mpg %>%
filter(manufacturer == "chevrolet")
fig1 <- plot_ly(audi, x = ~hwy, y = ~year, name = "", type = 'scatter',
mode = "markers", marker = list(color = "blue", symbol = 'x-dot'))
fig2 <- plot_ly(chevy, x = ~hwy, y = ~year, name = "", type = 'scatter',
mode = "markers", marker = list(color = "red", symbol = 'circle'))
fig <- subplot(fig1, fig2)
fig <- fig %>% subplot(shareX = TRUE,shareY = TRUE,which_layout = "merge")
fig <- fig %>% layout(
title = "Audi and Chevy",
xaxis = list(title = "Highway MPG"),
yaxis = list(title = "Year"),
margin = list(l = 100)
)
The only solution I've been able to find is tinkering with the width of the used subplot, but this leaves quite a bit of unused white space on the right and causes the title to be far off to the right (as it adjusts into the center of the used and unused subplots).
Is there a way to remove the unused subplot? If not, is there a way to organize/subset the dataframe such that only one plot needs to be used in the first place?
Thanks!
You can assign the colours based on the manufacturer column:
data.subs <- mpg %>%
filter(manufacturer == "audi" | manufacturer == "chevrolet")
fig <- plot_ly(data.subs, x = ~hwy, y = ~year, name = "",
type = 'scatter', mode = "markers",
marker = list(color = factor(data.subs$manufacturer,
labels = c("red", "blue")),
symbol = 'circle'),
text = factor(data.subs$manufacturer,
labels = c("audi", "chevy")), hoverinfo = 'text'))
fig <- fig %>% layout(
title = "Audi and Chevy",
xaxis = list(title = "Highway MPG"),
yaxis = list(title = "Year"),
margin = list(l = 100)
)
fig
This makes generating multiple subplots unnecessary.

Creating a line plot using plot_ly (R) with two y-axes

I am a newcomer to the plot_ly package and am trying to produce a time series line plot with two variables on the y axis.
In my dataframe 'baro' I have 'DateTime' variable in POSIXct format, and 'Pressure' and 'Temperature' in numeric format.
I am basing my code off the example given here: https://plot.ly/r/multiple-axes/
p <- plot_ly(baro)
add_trace(p, x = ~DateTime, y = ~Pressure, type = "scatter",
mode = "lines", name = "Pressure")
add_trace(p, x = ~DateTime, y = ~Temperature, type = "scatter",
mode = "lines", name = "Temperature", yaxis = "y2")
layout(p,
title = "Pressure & Temperature", yaxis2 = ay,
xaxis = list(title="x")
)
This outputs a set of axes labelled -1 to 6 on the x axis and -1 to 4 on the y axis with no data plotted.
I prefer use pipes %>% rather than attribute an object to a plot.
When you have 2 Y-axis it's nice to set the layout of every one explicitly.
This should do what you want:
# Build randon data
set.seed(123)
baro = data.frame(DateTime = as.POSIXct(1:10,origin = "2019-01-01"),
Pressure = sample(1000:2000,10),
Temperature = sample(20:60,10)
)
# Build plot
baro %>%
plot_ly(type = "scatter", mode = "lines") %>%
add_trace(x = ~DateTime, y = ~Pressure, name = "Pressure")%>%
add_trace(x = ~DateTime, y = ~Temperature, name = "Temperature", yaxis = "y2") %>%
layout(title = "Pressure & Temperature",
yaxis = list(title = "Pressure"),
yaxis2 = list(title = "Temperature",
overlaying = "y",
side = "right"
)
)
Here the output:
Best regards.

Traces not coming up properly when working on dual axis charts with plotly R

I have written below snippet of code to plot dual-axis charts using plotly in R.
Code:
## Date creation
dtMasterWithtotals <- data.table("Period_Month" = c('7/1/2017', '9/1/2017'), A = c(171, 448), B = c(0, 655), C = c(476, 812))
## Vectors to select categories for primary and secondary axis
vecPrimaryAxis <- c("A", "B")
vecSecondaryAxis <- c("C")
## X-axis properties
ax <- list(
type = "category",
categoryorder = "array",
categoryarray = dtMasterWithtotals[order(as.Date(dtMasterWithtotals[, Period_Month])),],
showgrid = TRUE,
showline = TRUE,
autorange = TRUE,
showticklabels = TRUE,
ticks = "outside",
tickangle = 0
)
## arrange columns in an order – TBD
## The plot function below assumes that the data will be in format, Period_Month, A, B,C.
## Plot function
plot <- plot_ly(dtMasterWithtotals, x = ~Period_Month, y = dtMasterWithtotals[[2]], type = "scatter", mode = 'lines', name = names(dtMasterWithtotals)[2])
if(length(vecPrimaryAxis) > 1){
t <- (3 + length(vecPrimaryAxis) - 2)
for (i in 3:t){
plot <- add_trace(plot, x = ~Period_Month, y = dtMasterWithtotals[[i]], type = "scatter", mode = "lines", name = names(dtMasterWithtotals)[i]) %>%
layout(xaxis = ax)
}
}
if(length(vecSecondaryAxis) > 0){
p <- 2 + length(vecPrimaryAxis)
q <- p + length(vecSecondaryAxis) - 1
for (j in (p:q)){
plot <- add_trace(plot, x = ~Period_Month, y = dtMasterWithtotals[[j]], type = "scatter", mode = "lines", yaxis = "y2", name = names(dtMasterWithtotals)[j]) %>%
layout(yaxis2 = list(overlaying = "y", side = "right"), xaxis = ax)
}
}
When trying to plot A and B on primary y-axis and C on secondary y-axis, the last trace (in this case C) overlaps the second trace (in this case B), resulting in two traces instead of three. However, on hover the new trace shows the correct value labels, but comes up incorrectly (at the wrong position) in the visualization.
Let me know if you require any other detail.
Thanks.
If I understand correctly what you want, in fact, there is no problem with your code. You just need to set manually your y and y2 axis. To make it easier to visualize I simply reversed the y2 axis. If you try this:
plot_ly() %>%
add_lines(data=dtMasterWithtotals, x = ~Period_Month, y = ~A, name = "A") %>%
add_lines(data=dtMasterWithtotals, x = ~Period_Month, y = ~B, name = "B") %>%
add_lines(data=dtMasterWithtotals, x = ~Period_Month, y = ~C, name = "C", yaxis = "y2") %>%
layout(xaxis = ax, yaxis2 = list(overlaying = "y", side = "right", autorange="reversed"))
It will give you this:
As you can see, all three lines are visible and all three displayed the right values.

Overlaying two histograms in R Plotly

I'm trying to overlay two histogram plots in R plotly. However only one of them shows up. Here's the code I'm using with some random data:
myDF <- cbind.data.frame(Income = sample(1:9, size = 1000, replace= TRUE),
AgeInTwoYearIncrements = sample(seq(from = 2, to = 70, by = 2), size = 1000, replace = TRUE))
plot_ly(data = myDF, alpha = 0.6) %>%
add_histogram(x = ~Income, yaxis = "y1") %>%
add_histogram(x = ~AgeInTwoYearIncrements, yaxis = "y2") %>%
layout(
title = "Salary vs Age",
yaxis = list(
tickfont = list(color = "blue"),
overlaying = "y",
side = "left",
title = "Income"
),
yaxis2 = list(
tickfont = list(color = "red"),
overlaying = "y",
side = "right",
title = "Age"
),
xaxis = list(title = "count")
)
Any help would be much appreciated!
It is the main cause to give the 1st yaxis overlaying. And because xaxis is count, Income and Age is y.
plot_ly(data = myDF, alpha = 0.6) %>%
add_histogram(y = ~Income, yaxis = "y1") %>% # not `x =`
add_histogram(y = ~AgeInTwoYearIncrements, yaxis = "y2") %>%
layout(
title = "Salary vs Age",
yaxis = list(
tickfont = list(color = "blue"),
# overlaying = "y", # the main cause is this line.
side = "left",
title = "Income"
),
yaxis2 = list(
tickfont = list(color = "red"),
overlaying = "y",
side = "right",
title = "Age"
),
xaxis = list(title = "count")
)
[Edited: just flip]
plot_ly(data = myDF, alpha = 0.6) %>%
add_histogram(x = ~ Income, xaxis = "x1") %>%
add_histogram(x = ~ AgeInTwoYearIncrements, xaxis = "x2") %>%
layout(
margin = list(t = 60),
title = "Salary vs Age",
xaxis = list(
tickfont = list(color = "blue"),
side = "left",
title = "Income"
),
xaxis2 = list(
tickfont = list(color = "red"),
overlaying = "x",
side = "top",
position = 0.95,
title = "<br>Age"
),
yaxis = list(title = "count")
)
You can mix histograms:
plot_ly(data = myDF, alpha = 0.6) %>%
add_histogram(x = ~Income) %>%
add_histogram(x = ~AgeInTwoYearIncrements) %>%
layout(
title = "Salary and Age",
yaxis = list(
tickfont = list(color = "blue"),
overlaying = "y",
side = "left",
title = "count"
),
xaxis = list(title = "Salary and Age value")
)
A histogram has normally on the y-axis the frequency / count and not on the x-axis. We can produce a diagram like you want but I'm not sure if it is still a histogram.
Also, like you see in my picture you the frequency/count for salary (here blue) is more high and the variability is less then age. That make it difficult for a good looking diagram. Maybe this is just a problem of your sample data...
So When you like to go with the histogram function, you have to invert the meaning of the frequency and the value on the x-axis.
But anyway, I think a scaternplot would be a better solution to show the relation between salary and age.
edit:
This is the result I get when I run your code:
Like this I don't see the sense in the plot and what you want. The meaning of the first orange colum is that a age of 59 occurs between 0 and 5 times in your dataset. The third colum means a age of 88 ocours between 10 and 15 times in your dataset.
To present this information in a barplot don't work. Because you can have several Age-values in on categorie of counts...I hope this is clear.
Anyway, to answer your question I need more clarification.
Following the responses here, I wanted to answer this with an example that others can easily use when for instance plotting two overlapping histograms.
# Add required packages
library(plotly)
# Make some sample data
a = rnorm(1000,4)
b = rnorm(1000,6)
# Make your histogram plot with binsize set automatically
fig <- plot_ly(alpha = 0.6) # don't need "nbinsx = 30"
fig <- fig %>% add_histogram(a, name = "first")
fig <- fig %>% add_histogram(b, name = "second")
fig <- fig %>% layout(barmode = "overlay",
yaxis = list(title = "Frequency"),
xaxis = list(title = "Values"))
# Print your histogram
fig
And here is the result of the code:
Easy way to handle any number of dimensions without repetition
TL;DR: You can rearrange your data to long-form before passing it to plot_ly().
df |>
mutate(row_number = row_number()) |>
pivot_longer(!row_number) |>
plot_ly() |>
add_histogram(x = ~ value,
color = ~ name,
opacity = 0.5) |>
layout(barmode = 'overlay')
Explanation
Given a DF with multiple columns, like the one the OP posted:
df = cbind.data.frame(Income = sample(1:9, size = 1000, replace= TRUE),
AgeInTwoYearIncrements = sample(seq(from = 2, to = 70, by = 2), size = 1000, replace = TRUE))
Then, using tidyr::pivot_longer():
df |> mutate(row_number = row_number()) |> pivot_longer(!row_number)
This gives:
# A tibble: 2,000 × 3
row_number name value
<int> <chr> <dbl>
1 1 Income 1
2 1 AgeInTwoYearIncrements 20
3 2 Income 1
4 2 AgeInTwoYearIncrements 48
5 3 Income 3
6 3 AgeInTwoYearIncrements 26
7 4 Income 4
8 4 AgeInTwoYearIncrements 30
9 5 Income 4
10 5 AgeInTwoYearIncrements 60
# … with 1,990 more rows
Finally, just pipe this to plot_ly(), so the full command is:
df |>
# Add a column to keep track of the row numbers
mutate(row_number = row_number()) |>
# Squash and lengthen the df with one row per row per column (in this case, double its length)
pivot_longer(!row_number) |>
plot_ly() |>
# The magic is here. We set color to track the name variable, which will
# add a separate series per column.
# We set the opacity so we can see where our plots overlap.
add_histogram(x = ~ value,
color = ~ name,
opacity = 0.5) |>
# Without setting this, bars will be plotted side by side for the same x value
# rather than overlapping.
layout(barmode = 'overlay')
Output

Resources