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
Related
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)))
I am trying to get another plot to react to both legend (select/deselect levels of a factor) and drag select. In the following toy example drag select works as intended: the violin and boxplot are re-rendered to depict the points that are selected using the mouse. The legend works for the scatterplot, but not for the boxplot and violin that don't seem to share the legend. I read many posts about shared legend, but nothing worked for subplots of different types.
Even more surprisingly, when deplying to plotly cloud, the plot also loses it's drag select feature (altough I don't need the plotly cloud, I thought I should mention this).
Just to be clear, I'd like the boxplot and violin to be re-rendered based both on selecting on legend and drag-select on scatterplot. As these features theoretically work, the legend should provide the full data or subsets based on levels of the factor used for legend from which the drag selection could be carried out afterwards.
library(plotly)
d <- mtcars
d$cyl <- as.factor(d$cyl)
d <- highlight_key(mtcars)
sp <- plot_ly(d, x = ~mpg, y = ~disp,
color = ~factor(cyl), colors = c("red", "green", "blue"),
legendgroup = ~factor(cyl), showlegend = T) %>%
add_markers()
box <-
plot_ly(d, y = ~disp,
color = I("black"),
legendgroup = ~factor(cyl), showlegend = F) %>%
add_boxplot(name = " ")
violin <-
plot_ly(d, y = ~disp,
color = I("black"),
legendgroup = ~factor(cyl), showlegend = F) %>%
add_trace(type = "violin", name = " ")
p <-
subplot(sp, box, violin, shareY = TRUE, titleX = TRUE, titleY = TRUE) %>%
layout(
dragmode = "select",
barmode = "overlay",
title = "Click and drag scatterplot",
showlegend = TRUE
) %>%
highlight(on = "plotly_selected", off = "plotly_deselect")
p
Any help is greatly appreciated.
I created the world map for the dataset I am working with however, the title of the plot is way above the chart and there is a huge space in between.
map_World <- list(
scope = 'world',
lakecolor = toRGB('white'))
Map4 <- plot_geo(regions) %>%
add_trace(
z = ~column1.x, locations = ~`ISO`,
color = ~column1.x, colors = c("red", "blue", "green")
) %>%
colorbar(title = "Legend",x = 1, y = 0.8) %>%
layout(title = "Sub indices for the different dimensions",
geo = map_World)
I expect the title to be right above the chart but it is not working.
I believe you can adjust the chart title attributes:
https://github.com/plotly/plotly.js/pull/3276
Try for your layout something like:
layout(title = list(text = "Sub indices for the different dimensions", y = 0.8),
geo = map_World)
I created a scatter plot with plotly in R. Now I want to plot a boxplot with different data next to the scatter plot. I want to use plotly for this.
The result should look like this. Can someone help me please, I have no idea how to do that.
My code so far is
plot_ly(ds, x = ~x, y = ~y , mode = "markers", name = "Clusters", opacity = point.opacity,
text = ds$id,
hoverinfo = "text",
marker = list(symbol = point.symbol, color = ~color, size = point.size,
line = list(color = "#262626", width = point.linewidth, opacity = point.lineopacity)),
showlegend = F)
Here is an example on how to make a scatter with marginal box plots with plotly:
library(plotly)
data(iris)
create, three plots for the data: one for the scatter, two for the appropriate box plots, and one additional empty plot. Use the subplot function to arrange them:
subplot(
plot_ly(data = iris, x = ~Petal.Length, type = 'box'),
plotly_empty(),
plot_ly(data = iris, x = ~Petal.Length, y = ~Petal.Width, type = 'scatter',
mode = 'markers'),
plot_ly(data = iris, y = ~Petal.Width, type = 'box'),
nrows = 2, heights = c(.2, .8), widths = c(.8,.2), margin = 0,
shareX = TRUE, shareY = TRUE) %>%
layout(showlegend = F)
I have just started using plotly in R and it is working great but I cannot figure out how to do two things.
1) I need to pick the colors of my split. Currently, I am splitting by Territory and plotly doesn't allow me to code what colors I want each territory to be.
2) I also need to scale the points so that some markers are very large. I tried creating a size for each row and setting size = ~size and sizes = c(2, 100) but this did not work.
Any advice on how to do this? I've tried reading the plotly R reference guide but cannot figure out how to do this with plotly_mapbox. I've pasted my code without the size or color attempt because I could never get it to work.
p <- df %>%
plot_mapbox(lat = ~lat, lon = ~lon,
split = ~Territory,
mode = 'scattermapbox',
text = df$text,
hoverinfo = "text"
) %>%
layout(title = 'Ship to Zip Codes',
font = list(color='white'),
plot_bgcolor = '#191A1A',
paper_bgcolor = '#191A1A',
mapbox = list(style = 'dark'),
legend = list(orientation = 'h',
font = list(size = 8)),
margin = list(l = 25, r = 25,
b = 25, t = 25,
pad = 2))
You can set the marker size via marker = list(size = 2).
Setting the colors is more tricky and cannot be done directly with plot_mapbox as far as I know.
But we can assign a new column to our data frame
df$colors <- factor(df$class, levels = unique(df$class))
then define our own color list
cols <- c("red", "blue", "black", "green", "orange", "cyan", "gray50")
and finally plot everything via plot_geo
plot_geo(df) %>%
add_markers(
x = ~reclong, y = ~reclat, color = ~colors, colors = cols, marker = list(size = 2))
The whole code to get the custom colors in a scatter map in Plotly.
library(plotly)
df = read.csv('https://raw.githubusercontent.com/bcdunbar/datasets/master/meteorites_subset.csv')
df$colors <- factor(df$class, levels = unique(df$class))
cols <- c("red", "blue", "black", "green", "orange", "cyan", "gray50")
plot_geo(df) %>%
add_markers(x = ~reclong,
y = ~reclat,
color = ~df$colors,
colors = cols,
marker = list(size = 2))