Is there a way to add an arrow image onto the side of a barchart, based on some underlying information?
I have the following script:
library(tidyverse)
library(plotly)
data <- tibble(url = c("google.com","yahoo.com","yandex.com"), values = c(500,400,300), change = c(0.5,-0.9,0.1))
data
data %>%
plot_ly(x = data$values,
y = data$url,
type = "bar")
This produces a simple bar chart in plotly, I would like to add some arrows next to each bar chart to show that the values have either decreased or increased based on the data$change
column. so if the number is positive a arrow turned up and green, if negative, then an arrow that is red and pointed down
Is this possible?
If none of this possible - is there a way to overlay just the text of the percentage change instead next to the bar charts?
Hopefully this would go onto a shiny app, so even if there is a way of embedding or overlaying a html element would be useful!
If there is an alternative in ggplot, I would also be interested.
Hopefully something that looks like this:
JUST TO UPDATE IN REGARDS TO BELOWS ANSWER THE CODE WOULD BE:
`library(tidyverse)
library(plotly)
data <- tibble(url = c("google.com","yahoo.com","yandex.com"), values = c(500,400,300), change = c(0.5,-0.9,0.1))
data
data %>%
plot_ly(x = data$values,
y = data$url,
type = "bar")
library(dplyr)
data <- data %>%
mutate(x.start = values + 50,
y.end = seq(0,2,1),
y.start = y.end + 0.5) %>%
mutate(y.start.new = case_when(sign(change) == -1 ~ y.end,
TRUE ~ y.start),
y.end.new = case_when(sign(change) == -1 ~ y.start,
TRUE ~ y.end)
)
data %>%
plot_ly(x = data$values,
y = data$url,
type = "bar") %>%
add_markers(~values, ~url) %>%
add_annotations(x = ~x.start[change == "up"],
y = ~y.start.new[change == "up"],
xref = "x", yref = "y",
axref = "x", ayref = "y",
text = "",
showarrow = T,
ax = ~x.start[change == "up"],
ay = ~y.end.new[change == "up"],
arrowcolor = "green") %>%
add_annotations(x = ~x.start[change == "down"],
y = ~y.start.new[change == "down"],
xref = "x", yref = "y",
axref = "x", ayref = "y",
text = "",
showarrow = T,
ax = ~x.start[change == "down"],
ay = ~y.end.new[change == "down"],
arrowcolor = "red")
`
But you do not produce the same output - only one arrow appears?