Overlaying two histograms in R Plotly - r

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

Related

Add average line/plot line to area highchart R

I know there are a few similar questions to this out there but they all seem to use javascript (?) or something besides the normal R coding so I don't know how to use it in my code... anyways all I want to do is add a plotline to my area chart that shows the average of the values, how do I do that? I know that highcharter itself can not calculate the average so I can do that myself but how do I create the plotline .... thank you so much. (i tried to make the code so that it is easily 'reproducible' ? hope it is ok). I attached a picture of the current chart if that helps.
library(tidyverse)
library(highcharter)
library(ggplot2)
data("diamonds", package = "ggplot2")
df <- diamonds %>%
group_by(cut)%>%
count()
head(df, 4)
# Create chart
hc <- df %>%
hchart(
'area', hcaes(x = cut, y = n),
color = "lightblue"
) %>%
hc_yAxis(title = list(text = "cut"))
# Display chart
hc
Below is a mini example of using the highcharts widget. You can add each series using hc_add_series. In this case, we have two series and two y-axes. Using two y-axes helps to differentiate between the series. I'm not sure what values you're trying to calculate the average so I chose price.
Hope this helps add some clarity to highcharter!
library(tidyverse)
library(highcharter)
df <- diamonds %>%
group_by(cut)%>%
summarise(
n = n(),
avg_price = round(mean(price),2)
)
# create hc widget
highchart(type = "chart") %>%
# add both series
hc_add_series(df, hcaes(x = cut, y = n), color = "lightblue", yAxis = 0, type = "area", name = "N") %>%
hc_add_series(df, hcaes(x = cut, y = avg_price), yAxis = 1, type = "line", name = "Avg Price") %>%
# set type to categories since we're looking at categorical data
hc_xAxis(type = "category", categories = df$cut) %>%
hc_title(text = "Cut Freq vs Avg Price") %>%
# add each y-axis which is linked above in 'hc_add_series'
hc_yAxis_multiples(
list(title = list(text = "Cut")), # yAxis = 0
list(title = list(text = "Average Price"), opposite = TRUE) # yAxis = 1
) %>%
hc_tooltip(shared = TRUE, split = FALSE)
Ex:
Haha I got it. basically just this.
plotline <- list(
color = "red", value = mean(diamonds$cut), width = 2, zIndex = 5
)
hc_yAxis(plotLines = list(plotline))

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.

Plotly bars with x-axis offset for timestamps

I want to plot some timestamps with plotly bars, with 1 bar indicating a whole hour.
My problem is that the ticks are centered in the middle and I would like to shift them to the left end of the bars.
When the plot isn't zoomed in, it's not such a problem, but when zooming in, more tick-labels will appear and they would be wrong.
EDIT: I need the option barmode = 'overlay' as I also have other traces to plot, which are not included in this example.
The picture below illustrates my current and exptected layout and here's some data to make that plot. (Some option I tried without success are also included in the xaxis configuration but uncommented).
library(plotly)
library(lubridate)
df <- data.frame(
ts = seq(as.POSIXct("2019-03-20 00:00:00"), by = "hour", length.out = 24),
val = sample(1:100, 24)
)
plot_ly() %>%
add_bars(data = df, x = ~ts, y = ~val) %>%
layout(dragmode = "select", autosize = TRUE, selectdirection = "h",
barmode = 'overlay',
bargap = 0.05,
xaxis = list(ticks = "outside",
type = "date",
# tickson="boundaries",
# offset=1800,
tickmode = "auto",
title = ""
)) %>%
config(scrollZoom = TRUE)
Would the following meet your needs?
One of the things that I take advantage of sometimes with plotly is that you can show different values in text that are independent of your the x and y values used to plot the data.
In this case, we can create a column with an offset time value, ts_x and plot the x values a half hour past the time for each row -- If you have a column for every hour, this effectively left-aligns the bars.
library(plotly)
df <- data.frame(
ts = seq(as.POSIXct("2019-03-20 00:00:00"), by = "hour", length.out = 24),
val = sample(1:100, 24)
)
## Create a dummy column with x offset values
df$ts_x <- df$ts + 1800
plot_ly() %>%
## Plot based on the dummy column
add_bars(data = df, x = ~ts_x, y = ~val,
## Cover up our tracks by not showing true x value on hoverinfo
hoverinfo = "text",
## Give text that includes the un-altered time values
text = ~paste0("Time: ",format(ts, format = "%B %d, %Y %H:%M"),
"<br>Value: ",val)) %>%
layout(dragmode = "select", autosize = TRUE, selectdirection = "h",
barmode = 'overlay',
bargap = 0.05,
xaxis = list(ticks = "outside",
type = "date",
tickmode = "auto",
title = ""
)) %>%
config(scrollZoom = TRUE)
By default, bars are centered, I didn't find how to change this.
One alternative is to add a second bar, because when there are 2 bars for each x-axis unity, one bar is at the left of the axis tick, and the second at the right (what you are trying to obtain with one bar).
Why not creating a second invisible bar ? :)
df <- data.frame(
ts = seq(as.POSIXct("2019-03-20 00:00:00"), by = "hour", length.out = 24),
val = sample(1:100, 24),
val0 = 0
)
plot_ly(df, type = 'bar') %>%
add_trace(x = ~ts, y = ~val0) %>%
add_trace(x = ~ts, y = ~val) %>%
layout(
showlegend = FALSE
) %>%
config(scrollZoom = TRUE)
This will create a legend (as there are 2 kind of bars, ones for val and ones for val0), so I removed it.
Are you sure you are not over engineering? Subtracting 30 minutes gives me a nice graph when zooming in.
I'm not suggest you actually edit the data, even if it's what I'm doing in the code. A small function in the call to add bars could solve it? If you overlay other data it could make a mess but I just wanted to suggest it.
library(plotly)
library(lubridate)
df2 <- data.frame(
ts = seq(as.POSIXct("2019-03-20 00:00:00"), by = "hour", length.out = 24) - minutes(30),
val = sample(1:100, 24)
)
plot_ly() %>%
add_bars(data = df2, x = ~ts, y = ~val) %>%
layout(dragmode = "select", autosize = TRUE, selectdirection = "h",
barmode = 'overlay',
bargap = 0.05,
xaxis = list(ticks = "outside",
type = "date",
# tickson="boundaries",
# offset=1800,
tickmode = "auto",
title = ""
)) %>%
config(scrollZoom = TRUE)

R programming Plotly bar chart grouped bars with multiple y axis

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?

Resources