2016-12-06 76 views
1

我想創建bar plot(與plotly包),其中(幾個月)將有red horizontal line(獲得收益)。我希望下面的情節更加精確地顯示我的問題。水平線在R情節,當x軸是離散的

enter image description here

代碼和數據需要獲得第一條曲線:

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')) 

我覺得我應該有連續的規模做到這一點,並在此之後只是改變x axis labels,但我不知道如何以改變這些標籤(當然,我試圖在谷歌中找到它)...

非常感謝您的幫助!

+0

你的代碼給我一個空的陰謀,你確定它是正確的嗎? –

+0

@ MarijnStevering,是的,我剛剛再次爲你檢查過 - 這是正確的。 – Marta

+0

啊,更新我的情節固定它,我的壞。 –

回答

1

會這樣的工作給你。您可以調整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) 
1

我已成功地建造你想用ggplot和美妙ggplotly()

通常這樣做是爲了ggplot標準導致懸停可怕的提示是什麼,但可以與text審美,並在該tooltip參數進行調整ggplotly通話

例如:

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") 

導致以下情節: enter image description here

+0

謝謝,但實際上我知道如何用'ggplot2'來做:)我有一些理由不使用'ggplotly()'。雖然,我不記得他們:)我正在尋找一些'plotly'的解決方案。 – Marta

+0

啊,那麼我沒有幫助,因爲我所有的'積極'的經驗是通過'ggplotly' –

+0

謝謝,無論如何:) – Marta