【发布时间】:2020-05-06 16:42:59
【问题描述】:
有没有办法根据一些基础信息在条形图的一侧添加箭头图像?
我有以下脚本:
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")
这会生成一个简单的条形图,我想在每个条形图旁边添加一些箭头,以显示基于data$change 列的值已经减少或增加。因此,如果数字为正,则箭头朝上并呈绿色,如果为负,则箭头朝下并呈红色
这可能吗?
如果这都不可能 - 有没有办法只覆盖百分比变化的文本而不是条形图旁边?
希望这会出现在一个闪亮的应用程序上,所以即使有一种嵌入或覆盖 html 元素的方法也会很有用!
如果 ggplot 有替代方案,我也会感兴趣。
希望是这样的:
仅更新以下代码:
`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")
`
但是您没有产生相同的输出 - 只出现一个箭头?
【问题讨论】: