I am ussing R Plotly and have a line of the form:
add_trace(y = meanRank,
x = DateOnly,
data = timeSeriesDF,
name = "Daily Value",
text = hoverText,
hoverinfo = "text",
showlegend = TRUE)
It works fine. However, I want this trace to be "unselected" when the plot is shown. So a user would click it on the legend to show the line. I can't seem to find the parameter to show that.
You could add visible = "legendonly":
library(plotly)
economics %>%
transform(rate = unemploy / pop) %>%
plot_ly(x = date, y = rate) %>%
loess(rate ~ as.numeric(date), data = .) %>%
broom::augment() %>%
add_trace(y = .fitted, name = "foo", visible = "legendonly")
See the reference.
you can use the attribute 'visible = legendonly' to other add_ functions such as:
add_lines(x = as.Date(x()$ds),
y = round(y()$total),
name = 'Inventory Total',
visible = 'legendonly')
Related
I am using Plotly to plot a scatterplot of GWAS data and want to highlight a certain point a different colour to the rest of the data. I have tried multiple times but unable to find away around this in Plotly. Any advice would be great please.
input data looks like this:
fig <- fig %>% add_trace(data=data_1, x = ~BP, y = ~log, name = "data", mode = "markers", type = "scatter",
y = c(117300000, 117900000), marker = list(size = 8, color = '#d62728'),
x = c(117558703), y = c(19.75696195), marker = list(color = 'blue',size = 8), type = "scatter")
fig
One of the easiest ways is to create a variable to identify that specific point. I created sample data here and assigned a colour variable equal to 1 for the point I want in another color.
df = tibble(bp = round(rnorm(10,5,2),2),
log = round(rnorm(10,6,1.5),2))
df$colour <- as.factor(ifelse(df$bp == 4.41,1 ,0))
fig <- plot_ly(data = df, x = ~bp, y = ~log, group_by = ~colour,marker = list(color = factor(df$colour,labels=c("red","purple")))) %>%
add_trace(data = df, x = ~bp, y = ~log, mode = 'markers', type = 'scatter')
fig
Link to plot produced by this code
One option to achieve your desired result would be to add an indicator variable to your data to indicate which points you want to highlight. This variable could then be mapped on the color attribute. The colors could then be set via the colors attribute.
Using a minimal reproducible example base on mtcars:
library(plotly)
data_1 <- mtcars
data_1$highlight <- row.names(data_1) %in% c("Honda Civic", "Porsche 914-2")
plot_ly() %>%
add_trace(
data = data_1, x = ~hp, y = ~mpg, color = ~highlight,
mode = "markers", type = "scatter",
marker = list(size = 8), colors = c("#d62728", "blue")
)
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))
I am trying to split the attached grouped bar chart by the variable spec. Two thoughts on best way to do this are by adding facet_grid() or if a filter can be applied to the static output? Can either be done? Any advice appreciated.
a sample is below:
period <- c('201901', '201901', '201904', '201905')
spec <- c('alpha', 'bravo','bravo', 'charlie')
c <- c(5,6,3,8)
e <- c(1,2,4,5)
df <- data.frame(period, spec, c,e)
library(tidyverse)
library(plotly)
plot_ly(df, x =~period, y = ~c, type = 'bar', name = "C 1", marker = list(color = 'lightsteelblue3'))
%>%
add_trace(y = ~e, name = "E 1", marker = list(color = 'Gray')) %>%
layout(xaxis = list(title="", tickangle = -45),
yaxis = list(title=""),
margin= list(b=100),
barmode = 'group'
)
I am not sure if you are plotting what you actually want to achieve? My suggestion is to create your plot using standard ggplot and then use ggplotly.
For this, you also need to reshape your data and make it a bit longer.
library(tidyverse)
library(plotly)
period <- c('201901', '201901', '201904', '201905')
spec <- c('alpha', 'bravo','bravo', 'charlie')
c <- c(5,6,3,8)
e <- c(1,2,4,5)
df <- data.frame(period, spec, c,e) %>%
pivot_longer(cols = c(c,e), names_to = 'var', values_to = 'val')
p <- ggplot(df, aes(period, val, fill = var)) +
geom_col(position = position_dodge()) +
facet_grid(~spec)
ggplotly(p)
It's probably easier to use facets here, but a more "interactive" option would be to use a filter transforms which gives you a drop-down menu in the top left corner of your plot.
spec.val <- unique(df$spec)
plot_ly(
df %>% pivot_longer(-c(period, spec)),
x = ~period, y = ~value, color = ~name,
type = "bar",
transforms = list(
list(
type = "filter",
target = ~spec,
operation = "=",
value = spec.val[1]))) %>%
layout(
updatemenus = list(
list(
type = "drowdown",
active = 0,
buttons = map(spec.val, ~list(
method = "restyle",
args = list("transforms[0].value", .x),
label = .x)))))
I am building a stacked bar chart in plotly and whenever I run my loop for add_trace, there is an issue as data of the previous trace seems to dissapear while names remain.
p = plot_ly( x = rownames(dist_data), y = as.numeric(dist_data[,1]), type = 'bar', name = colnames(dist_data)[1])%>%
layout(legend = list(x = 0.1, y = 0.9))
for ( j in 2:length(colnames(dist_data)))
{
p = add_trace(p, y = ~as.numeric(dist_data[,j]), type = 'bar',name = colnames(dist_data)[j]) %>%
layout( barmode = 'stack')
}
p
I am wondering whether there is something wrong in the loop.
When trying manually for adding trace1, works fine. When adding trace 2 (j=3), trace1's values become automatically equal to trace2's value.
UPD: When using dplyr, I have issues with some other parts of my code.
Is there a solution without it?
Thank you for the help,
You are overwriting p at each loop iteration. Try:
p = p %>% add_trace(y = ~as.numeric(dist_data[,j]), type = 'bar',name = colnames(dist_data)[j]) %>%
layout( barmode = 'stack')
2nd Edit:
not sure why this is happening. It works if you reshape to a long format dataframe which is better practice than using a for loop:
mtcars %>%
mutate(id = rownames(.)) %>%
gather(key = "variable",value = "value",-id) %>%
plot_ly(x = ~id, y=~value, type="bar", color=~variable) %>%
layout(barmode = "stack")
Edit:
dist_data=mtcars
p = plot_ly( x = rownames(dist_data),
y = as.numeric(dist_data[,1]),
type = 'bar', name = colnames(dist_data)[1]) %>%
layout(legend = list(x = 0.1, y = 0.9))
for ( j in 2:length(colnames(dist_data))){
p = add_trace(p, y = ~as.numeric(dist_data[,j]),
type = 'bar',name = colnames(dist_data)[j]) %>%
layout( barmode = 'stack')
}
p
I am making a pie-chart in plotly in R.
I want my labels to be on the chart, so I use textposition = "inside", and for the very small slices those values are not visible.
I am trying to find a way to exclude those labels.
Ideally, I would like to like to not print any lables on my plot that are below 10%.
Setting textposition = "auto" doesn't work well, since there are a lot of small slices, and it makes the graph look very messy.
Is there a way to do it?
For example these piecharts from plotly website (https://plot.ly/r/pie-charts/)
library(plotly)
library(dplyr)
cut <- diamonds %>%
group_by(cut) %>%
summarize(count = n())
color <- diamonds %>%
group_by(color) %>%
summarize(count = n())
clarity <- diamonds %>%
group_by(clarity) %>%
summarize(count = n())
plot_ly(cut, labels = cut, values = count, type = "pie", domain = list(x = c(0, 0.4), y = c(0.4, 1)),
name = "Cut", showlegend = F) %>%
add_trace(data = color, labels = color, values = count, type = "pie", domain = list(x = c(0.6, 1), y = c(0.4, 1)),
name = "Color", showlegend = F) %>%
add_trace(data = clarity, labels = clarity, values = count, type = "pie", domain = list(x = c(0.25, 0.75), y = c(0, 0.6)),
name = "Clarity", showlegend = F) %>%
layout(title = "Pie Charts with Subplots")
In the plot for Clarity 1.37% are outside of the plot, while I would like them not to show at all.
You'll have to specify sector labels manually like so:
# Sample data
df <- data.frame(category = LETTERS[1:10],
value = sample(1:50, size = 10))
# Create sector labels
pct <- round(df$value/sum(df$value),2)
pct[pct<0.1] <- 0 # Anything less than 10% should be blank
pct <- paste0(pct*100, "%")
pct[grep("0%", pct)] <- ""
# Install devtools
install.packages("devtools")
# Install latest version of plotly from github
devtools::install_github("ropensci/plotly")
# Plot
library(plotly)
plot_ly(df,
labels = ~category, # Note formula since plotly 4.0
values = ~value, # Note formula since plotly 4.0
type = "pie",
text = pct, # Manually specify sector labels
textposition = "inside",
textinfo = "text" # Ensure plotly only shows our labels and nothing else
)
Check out https://plot.ly/r/reference/#pie for more information...