R语言 地块子地块对每个地块应用不同的比例

5vf7fwbs  于 2023-05-04  发布在  其他
关注(0)|答案(2)|浏览(157)

我想使用plotly::subplot创建一个背靠背图,代码如下:

library(plotly)

df <- data.frame(x = c("A", "B", "C"), a = c(0.1, 0.2, 0.3), b = c(0.1, 0.2, 0.6))

p1 <- plot_ly(df) %>% 
  add_bars(x = ~a, y = ~x) %>% 
  layout(xaxis = list(tickformat = ".0%", autorange = "reversed"))

p2 <- plot_ly(df) %>% 
  add_bars(x = ~b, y = ~x) %>% 
  layout(xaxis = list(tickformat = ".0%"))

subplot(p1, p2, shareY = TRUE, shareX = TRUE, nrows = 1, margin = 0)

我的问题是,x轴上的10%比例在左边的宽度与它在右边的宽度不同。怎么解决呢?

tez616oj

tez616oj1#

p1中使用反向范围列表range = list(0.6, 0),而不是autorange

library(plotly)

p1 <- plot_ly(df) %>% 
  add_bars(x = ~a, y = ~x) %>% 
  layout(xaxis = list(tickformat = ".0%", range = list(0.6, 0)))

p2 <- plot_ly(df) %>% 
  add_bars(x = ~b, y = ~x) %>% 
  layout(xaxis = list(tickformat = ".0%"))

subplot(p1, p2, shareY = TRUE, shareX = TRUE, nrows = 1, margin = 0)

要缩小p1上的x轴范围,请使用scaleanchor。在这种情况下,我们可以将autorange = "reversed"保留在p1中。但是,subplot中的margin = 0参数在设置此参数后似乎不起作用。因此,我们可能需要将margin操作为负值,并设置刻度间隔(tickvals),以避免在“0%”上重叠标签。

p1 <- plot_ly(df) %>% 
  add_bars(x = ~a, y = ~x) %>% 
  layout(xaxis = list(tickformat = ".0%", autorange = "reversed"))

p2 <- plot_ly(df) %>% 
  add_bars(x = ~b, y = ~x) %>% 
  layout(xaxis = list(tickformat = ".0%"))

subplot(p1, p2, shareY = TRUE, shareX = TRUE, nrows = 1, margin = -0.07) %>% 
  layout(xaxis = list(scaleanchor = "x2"), xaxis2 = list(tickvals = list(0.2, 0.4, 0.6)))

t8e9dugd

t8e9dugd2#

我们也可以通过将列a中的值转换为负值,然后将数据重新整形为更长的格式来实现这一点。然后,一个带有barmode = "relative"的图将给予我们想要的结果。根据需要更改边距、边距和轴限制。

library(plotly)
library(dplyr)
library(tidyr)

data.frame(x = c("A", "B", "C"), a = c(0.1, 0.2, 0.3), b = c(0.1, 0.2, 0.6)) %>% 
  mutate(a = -a) %>% 
  pivot_longer(-x) %>% 
plot_ly(x = ~value, y= ~x, type = 'bar', color= ~name) %>%
  layout(barmode = 'relative',
         xaxis = list(tickformat = ".0%"))

相关问题