Plotly-R: How to make a gapped y axis?

*爱你&永不变心* 提交于 2021-01-24 13:47:06

问题


Is it possible to create a plotly bar chart, e.g. any chart from the following website: https://plotly.com/r/bar-charts/ but with the gapped (broken) Y axis? An example from (ggplot2, I believe) attached below:


回答1:


To my knowledge, plotly hasn't got any built-in functionality to do this. But it's still possible to make a figure that matches your image using subplots if you:

  1. use subplot(fig1, fig2, nrows = 2, shareX=TRUE, margin = <low>), and

  2. adjust the y axes for figure positions [1, 1] and [2, 1] to respectively start and end with your desired cutoff values in a defined interval.

Plot:

Complete code:

library(dplyr)
library(plotly)


years <- c(1995, 1996, 1997, 1998, 1999, 2000,2001, 2002, 2003, 2004, 2005, 2006,2007, 2008, 2009, 2010, 2011, 2012)
China <-  c(219, 146, 112, 127, 124, 180, 236,207, 236, 263,350, 430, 474, 1526,488, 537, 500, 439)
Rest_of_World <- c(16, 13, 10, 11, 28, 37,43, 55, 56, 88, 105, 156, 270,299, 340, 403, 549, 1499)
df <- data.frame(years, China, Rest_of_World)

colors <- c('rgb(31, 119, 180)',
 'rgb(255, 127, 14)',
 'rgb(44, 160, 44)',
 'rgb(214, 39, 40)',
 'rgb(148, 103, 189)',
 'rgb(140, 86, 75)',
 'rgb(227, 119, 194)',
 'rgb(127, 127, 127)',
 'rgb(188, 189, 34)',
 'rgb(23, 190, 207)')

cutinterval = c(600, 1400)

fig1 <- plot_ly(df, type = 'bar')
fig1 <- fig1 %>% add_trace(x=years, y=China, #yaxis = list(range = c(0, 400)),
                           marker=list(color = 'red'),
                           name = 'China',
                           legendgroup='China')
fig1 <- fig1 %>% add_trace(x=years, y=Rest_of_World,
                           marker=list(color = 'blue'),
                           name = 'Rest of World',
                           legendgroup='Rest_of_World')

fig2 <- plot_ly(df, type = 'bar')
fig2 <- fig2 %>% add_trace(x=years, y=China, #yaxis = list(range = c(1400, 1600)),
                           marker=list(color = 'red'),
                           legendgroup='China',
                           showlegend=FALSE)
fig2 <- fig2 %>% add_trace(x=years, y=Rest_of_World,
                           marker=list(color = 'blue'),
                           legendgroup='Rest_of_World',
                           showlegend=FALSE)
list(range = c(0, cutinterval[1]))

fig1 <- fig1 %>% layout(barmode = 'group')
fig <- subplot(fig1, fig2,nrows = 2, shareX=TRUE, margin = 0.02)

fig <- layout(fig, yaxis2 = list(range = c(0, cutinterval[1])),
                   yaxis = list(range = c(cutinterval[2], 1600))
                   #shapes = list(hline(1500))
              )


fig


来源:https://stackoverflow.com/questions/65669385/plotly-r-how-to-make-a-gapped-y-axis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!