本文介绍了Plotly-R:如何制作有间隙的y轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个可绘制的条形图,例如来自以下网站的任何图表:

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:

推荐答案

据我所知,plotly没有任何内置功能来执行此操作.但是,如果您进行以下操作,仍然可以使用子图制作与您的图像匹配的图形:

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. 使用子图(fig1,fig2,nrows = 2,shareX = TRUE,margin =< low>)

调整图形位置 [1,1] [2,1] 的y轴,分别以所需的截止值开始和结束定义的时间间隔.

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.

情节:

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

这篇关于Plotly-R:如何制作有间隙的y轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 16:15