【问题标题】:Horizontal line in R plotly, when xaxis is discrete当x轴是离散的时,R中的水平线
【发布时间】:2017-04-21 02:34:35
【问题描述】:

我想创建一个bar plot(带有plotly 包),它(几个月)将有red horizontal line(获得)。我希望下面的图表更准确地显示了我的问题。

获取第一个绘图所需的代码和数据:

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,但我不知道如何更改这些标签(我已经尝试先在谷歌中找到它,当然) ...

非常感谢您的帮助!

【问题讨论】:

  • 你的代码给了我一个空白的情节,你确定它是正确的吗?
  • @MarijnStevering,是的,我刚刚为您再次检查过 - 正确。
  • 啊,更新我的阴谋修复它,我的错。
  • 不运行代码,你的问题在我看来就像可以用 ggplot2 中的group 处理的东西......我不知道情节上的等价物是什么,但也许这值得一看?

标签: r plotly r-plotly


【解决方案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) 

【讨论】:

    【解决方案2】:

    我已经设法使用ggplot 和奇妙的ggplotly() 构建了您想要的东西

    为 ggplot 标准正常执行此操作会导致悬停时出现可怕的工具提示,但这可以通过 text 美学和 ggplotly 调用中的 tooltip 参数进行调整

    例如:

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

    结果如下图:

    【讨论】:

    • 谢谢,但实际上我知道如何使用ggplot2 :) 我有一些理由不使用ggplotly()。虽然,我真的不记得他们了 :) 我正在寻找一些 plotly 的解决方案。
    • 啊,那我也没用,因为我所有的plotly 经验都是通过ggplotly 完成的
    猜你喜欢
    • 2016-05-14
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多