r - 在双轴图上绘制不同级别的零线

标签 r graph data-visualization plotly

我试图在 plotly 中叠加一个折线图和条形图(用一条垂直线指定一个重要的日期),我遇到了两个零线偏移而不是在同一条线上的问题。我试过搞乱 overlaying = 'y' layout 内的选项并尝试更改三个 trace 的顺序组件,但似乎没有任何帮助。任何想法如何解决?下面是我的带有虚拟数据的代码:

(此外,如果您能解决我的图例重叠 y2axis 问题,则加分)

date <- seq(as.Date("2015/6/1"), by = "month", length.out = 19) 
wires_mnth <- c(rep(0,8),100000,750000,1200000,2500000,3100000,5500000,7500000,8000000,9900000,11300000,11000000)
wires_cnt <- c(rep(0,8),100,200,250,325,475,600,750,800,1000,1150,1200)
data <- data.frame(date, wires_mnth)

plot_ly(data) %>%
add_trace(x = ~date, y = ~wires_cnt, type = 'bar', name = 'Wires Count', 
    yaxis = 'y2', opacity = .5) %>%
add_trace(x = ~date, y = ~wires_mnth, type = 'scatter', mode = 'lines', name 
    = 'Monthly Wires') %>%
add_trace(x = c(2016,2016), y = c(0, 12000000), type = 'scatter', mode = 
    "lines", name = 'Sanctions Removed') %>%

layout(title = 'Monthly Aggregate Wire Transfers to Iran',
     xaxis = list(title = ''),
     yaxis = list(side = 'left', title = 'Wire Amounts (USD)', showgrid = 
         FALSE, zeroline = FALSE),
     yaxis2 = list(side = 'right', overlaying = 'y', title = 'Wires Count', 
        showgrid = FALSE, zeroline = FALSE)
     )

enter image description here

最佳答案

您可以添加 rangemode='nonnegative' 给您的 layout或指定 range 手动通过 range=list(0, max(wires_mnth) .

对于您的奖金问题,您可以设置 x-position传说中的,例如legend = list(x = 1.2)
enter image description here

关于r - 在双轴图上绘制不同级别的零线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46936223/

相关文章:

r - 将连续的数字折叠为一串范围

代码运行正常但调试给出 "Segmentation fault"

java - Java 中的标记图表示

graph - 子图与 SAT 同构

d3.js - 在哪里可以找到折线图的良好标签放置算法?

python - 使用子图绘制水平线 Matplotlib

r - 在 R 的循环中将字符串视为对象名称

R Shiny - 条件面板中的条件面板

r - ggplot2 绘图区域边距?

r - 使用数据类型名称列表更改数据类型