[英]Horizontal line in R plotly, when xaxis is discrete
I would like to create a bar plot
(with the plotly
package), which (for some months) would have red horizontal line
(gain to obtain). 我想创建一个
bar plot
(使用plotly
程序包),该plotly
(几个月内)将具有red horizontal line
(获取)。 Plots below show my problem more precisely, I hope. 我希望下面的图更精确地显示我的问题。
Code and data needed to obtain first plot: 获取第一幅图所需的代码和数据:
library("plotly")
library("dplyr")
data.frame(miesiac_label = as.character(as.roman(c(1:12))),
miesiac = c(1:12),
ile = c(12000, 12100, 11100, 12000, 12000, 11900, 12200, 12100, 6000, 12100, 12100, 12100),
gain = c(rep(NA, 7), 11000, 12000, 12000, 12000, 12000)) -> dane
dane$miesiac_label <- factor(dane$miesiac_label, levels = dane[["miesiac_label"]])
plot_ly(dane) %>%
add_trace(x = ~miesiac_label, y = ~ile,
type = 'bar', marker = list(color = '#99d3df')) %>%
add_trace(x = ~miesiac_label, y = ~gain, name = 'Gain',
type = "scatter", mode='lines+markers', marker = list(color = 'red'),
line = list(color = 'red'))
I think that I should have a continuous scale to do this and after this just change x axis labels
, but I don't know how to change those labels (I've tried to find it in google first, of course)... 我认为我应该有一个连续的比例来执行此操作,然后更改
x axis labels
,但是我不知道如何更改这些标签(当然,我首先尝试在Google中找到它)...
Thanks a lot for your help! 非常感谢你的帮助!
Would something like that work for you. 这样的事情对您有用吗? You could adjust the numbers in
add_segments
. 您可以调整
add_segments
的数字。
a <- list(
title = "miesiac_label",
showticklabels = TRUE,
tickmode= "array",
ticktext = as.character(as.roman(c(1:12))),
tickvals = c(1:12)
)
plot_ly(dane) %>%
add_bars(x = ~miesiac, y = ~ile) %>%
add_segments(x = 7.5, xend = 8.5, y = 10000, yend = ~10000, line = list(dash = "dash")) %>%
add_segments(x = 8.5, xend = 12.5, y = 12000, yend = ~12000, line = list(dash = "dash")) %>%
layout(showlegend = FALSE, xaxis = a)
I have managed to construct what you want using ggplot
and the fantastic ggplotly()
我设法使用
ggplot
和出色的ggplotly()
构造了您想要的ggplot
Doing it normally for ggplot standards leads to hideous tooltips on hover, but that can be tweaked with the text
aesthetic and the tooltip
argument in the ggplotly
call 通常对ggplot标准执行此操作会导致悬停时出现可怕的工具提示,但是可以通过
ggplotly
调用中的text
美感和tooltip
参数进行调整
for example: 例如:
ggplot(dane, aes(x = miesiac_label, y = ile)) +
geom_bar(aes(text = paste("x:", miesiac_label, "y:",ile)),
stat = "identity", fill = "#99d3df") +
geom_segment(aes(x = miesiac - 0.5, xend = miesiac + 0.5,
y = gain, yend = gain,
text = paste0("gain: ",gain))
, colour = "red"
, linetype = 2)
ggplotly(tooltip = "text")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.