Colorscale in plotly() - r

I am tring to create plotly bar plot with scalling colors.
I have found out how to adjust color scaling by variable, but don't know how to choose another pallet. I would like to use RBrewerPallet for example.
Here is an example.
library(plotly)
library(dplyr)
airquality %>% group_by(Month) %>% summarise(total = sum(Wind)) %>%
plot_ly(x = ~Month,
y = ~total,
type = 'bar',
marker = list(
color = ~total
))

Here is a way to specify the color scale for bar charts in plotly:
library(plotly)
library(dplyr)
airquality %>% group_by(Month) %>% summarise(total = sum(Wind)) %>%
plot_ly(x = ~Month,
y = ~total,
type = 'bar',
marker = list(
color = ~total,
colorscale='Blues'
))
I know of these palletes: "Blackbody", "Bluered", "Blues", "Earth", "Electric", "Greens", "Greys", "Hot", "Jet", "Picnic", "Portland", "Rainbow", "RdBu", "Reds", "Viridis", "YlGnBu", "YlOrRd".
if not enough you can manually specify:
marker = list(color = c('rgba(204,204,204,1)', 'rgba(222,45,38,0.8)',
'rgba(204,204,204,1)', 'rgba(204,204,204,1)',
'rgba(204,204,204,1)')

Related

Single color plotly map

How can I render a plotly map with only a single color. In the example below, I would like the fill for all states to be red, or #FF0000.
library(plotly)
library(tidyverse)
dat <- data.frame(state = state.abb)
plot_ly(dat,
type = "choropleth",
locationmode = 'USA-states',
locations = ~state) %>%
add_trace(color = "red") %>%
layout(geo = list(
projection = list(
type = "albers usa")))
From what I understand of the plotly documentation this is a way to achive it (cloropleth is kind of heatmap but you want one color for all):
library(plotly)
dat <- data.frame(state = state.abb)
plot_ly(dat,
type = "scattergeo",
mode = 'none',
locationmode = 'USA-states',
locations = ~state) %>%
layout(geo = list(landcolor = "#FF0000",
showland = TRUE,
projection = list(type = "albers usa")))

R plot_ly: How display discrete & non-discrete data on same axis?

I am working on a stacked bar plot for the following data set, and get an error "Can't display both discrete & non-discrete data on same axis". Also, data is not plotted correctly. For each "month" on X-axis, I expect to have stacked bars by "unit" with values from "value".
library(data.table)
library(plotly)
df <- fread(
'"month","unit","value"
"2017-01","Unit 1",1064000
"2017-01","Unit 2",911487
"2017-02","Unit 1",851200
"2017-02","Unit 2",656640
"2017-03","Unit 1",834905
"2017-03","Unit 2",601920')
df %>%
plot_ly(x = ~month, y = ~value, type = 'bar', name = "month") %>%
add_trace(y = ~unit, name = "unit") %>%
layout(yaxis = list(title = 'Units by dates'), barmode = 'stack')
I will be highly appreciated if someone knows how to make workable plots here.
Thanks!
You don't have to add a trace for a simple barplot it's easier to define a color-argument.
df %>%
plot_ly(x = ~month, y = ~value, color = ~unit, type = "bar") %>%
layout(yaxis = list(title = 'Units by dates'), barmode = 'stack')

Separate symbol and color in plotly legend

I want to achieve the same result as this ggplot code with plotly:
mtcars %>% add_rownames('car') %>%
ggplot(aes(x = mpg,
y = disp,
color = as.factor(gear),
shape = as.factor(cyl))) +
geom_point()
which results in:
My plotly code is:
library(dplyr)
mtcars %>% add_rownames('car') %>%
plot_ly(x = ~mpg,
y = ~disp,
text = ~car,
color = ~as.factor(gear),
symbol = ~as.factor(cyl),
mode = 'markers')
which enumerates all possible combinations of colors and shapes in the legend.
Is there a way to have a similar legend to the ggplot?
UPDATE: To overcome some of the issues mentioned for my previous solution (see below) and to increase the usability of the legend, one can simply add the column name to the legend description and then assign the legendgroups to each category.
mtcars %>% rownames_to_column('car') %>%
plot_ly() %>%
#Plot symbols for cyl
add_trace(type = "scatter",
x = ~mpg,
y = ~disp,
text = ~car,
symbol = ~paste0(cyl," cyl."),
mode = 'markers',
marker = list(color = "grey", size = 15)) %>%
#Overlay color for gears
add_trace(type = "scatter",
x = ~mpg,
y = ~disp,
text = ~car,
color = ~paste0(gear, " gears"),
mode = 'markers')
This is the previous solution, which is visually closer to the ggplot2 equivalent:
Based on the answer of dww in this thread, we can manually create the groups for cylinders and gears. Subsequently, with the answer of Artem Sokolov this thread, we can add the legend titles as annotations.
mtcars %>% rownames_to_column('car') %>%
plot_ly() %>%
#Plot symbols for cyl
add_trace(type = "scatter",
x = ~mpg,
y = ~disp,
text = ~car,
symbol = ~as.factor(cyl),
mode = 'markers',
legendgroup="cyl",
marker = list(color = "grey", size = 15)) %>%
#Overlay color for gears
add_trace(type = "scatter",
x = ~mpg,
y = ~disp,
text = ~car,
color = ~as.factor(gear),
mode = 'markers',
legendgroup="gear") %>%
#Add Legend Titles (manual)
add_annotations( text="Cylinders:", xref="paper", yref="paper",
x=1.02, xanchor="left",
y=0.9, yanchor="bottom", # Same y as legend below
legendtitle=TRUE, showarrow=FALSE ) %>%
add_annotations( text="Gears:", xref="paper", yref="paper",
x=1.02, xanchor="left",
y=0.7, yanchor="bottom", # Y depends on the height of the plot
legendtitle=TRUE, showarrow=FALSE ) %>%
#Increase distance between groups in Legend
layout(legend=list(tracegroupgap =30, y=0.9, yanchor="top"))
Unsolved issues:
Groups have to be created manually
Groups are just overlayed (color over shape). This means that only the whole group can be dis-/activated in the legend (e.g., it is not possible to only show only the entries with 4 cylinders)
The position of the second legend title (annotation) depends on the height of the plot!

setting specific color palettes for individual traces in plotly chart

i'm trying to define a specific color palette for each individual trace of a chart in plotly in r. my code is as follows:
library(ggplot2)
library(dplyr)
library(plotly)
colors_1 <- c("#2e71c9","#ffb728")
colors_2 <- c("#4f4f4f","#000000")
data_subset_1 <-
diamonds %>%
filter(clarity %in% c("VVS2", "VS1")) %>%
mutate(cut = as.character(cut)) %>%
count(cut, clarity)
data_subset_2 <-
diamonds %>%
filter(clarity %in% c("SI1", "IF")) %>%
mutate(cut = as.character(cut)) %>%
count(cut, clarity)
plot_ly() %>%
add_bars(data = data_subset_1, x = ~cut, y = ~n, color = ~clarity, colors = colors_1) %>%
add_bars(data = data_subset_2, x = ~cut, y = ~n, color = ~clarity, colors = colors_2)
the bars of the first trace should be in blue and orange, the 2nd trace in grey and black, but clearly they all are all in color. if i remove the colors = colors_2 from the second trace, it does not even change anything at all. it seems the colors defined in the first trace are being used to calculate a color palette that is used for all traces of the plot, but i'd like to specifically assign color palettes.
Try the following:
cols <- setNames(c("#2e71c9","#ffb728", "#CCDDDD","#000000"),
c("VVS2", "VS1", "SI1", "IF"))
plot_ly() %>%
add_bars(data = data_subset_1, x = ~cut, y = ~n, color = ~clarity, colors = cols) %>%
add_bars(data = data_subset_2, x = ~cut, y = ~n, color = ~clarity)

Change locale in Plotly for R (thousand separator and decimal character)

I'd like to adjust the tick labels in a plotly chart so that they would display a comma as a decimal separator and a point as a thousand separator.
library(plotly)
library(ggplot2)
library(dplyr)
diamonds %>%
mutate(cut = as.character(cut)) %>%
count(cut, clarity) %>%
plot_ly(x = ~cut, y = ~n, color = ~clarity) %>%
layout(yaxis = list(tickformat = ",.1f"))
my local is already set to "LC_COLLATE=German_Austria.1252;LC_CTYPE=German_Austria.1252;LC_MONETARY=German_Austria.1252;LC_NUMERIC=C;LC_TIME=C"
This is an ugly answer but you can set up your object:
d2 <- diamonds %>%
mutate(cut = as.character(cut)) %>%
count(cut, clarity)
and then create the axis labels from there:
ticklabels <- seq(from=0, to=round(max(d2$n), digits = -3), by=1000)
To create a custom axis label:
plot_ly(d2, x = ~cut, y = ~n, color = ~clarity) %>%
layout(yaxis = list(tickvals = ticklabels, ticktext = paste(ticklabels/1000, ".000", ",00", sep="") ))

Resources