我目前正在使用plotly. 以下是示例資料集:
library(tidyverse)
library(plotly)
library(hrbrthemes)
set.seed(9999)
df <- data.frame(group.int = rep(c(rep("Prevention", 3), "Diagnosis", rep("Intervention", 2)), 6),
int = rep(c("Prevention 1", "Prevention 2", "Prevention 3", "Diagnosis 1", "Intervention 1", "Intervention 2"), 6),
group.outcome = c(rep("Efficacy", 12), rep("Safety", 18), rep("Cost-effectiveness", 6)),
outcome = c(rep("Efficacy 1", 6), rep("Efficacy 2", 6), rep("Safety 1", 6), rep("Safety 2", 6), rep("Safety 3", 6), rep("Cost-effectiveness 1", 6)),
n = sample(50:250, 36, rep = TRUE)
)
df$group.int <- factor(df$group.int, levels = c("Prevention", "Diagnosis", "Intervention"))
df$group.outcome <- factor(df$group.outcome, levels = c("Efficacy", "Safety", "Cost-effectiveness"))
我想根據變數來制作一個熱圖,作為每個熱圖單元格的填充outcome。這是所需的情節:intn

我嘗試ggplotly從創建的 ggplot 中使用:
plotly.df <- ggplot(df,
aes(x = int, y = outcome, fill= n))
geom_tile()
scale_fill_gradient(low="white", high="darkred")
scale_y_discrete(position = "right")
facet_grid(group.outcome ~ group.int,
scales = "free", space = "free", switch = "x")
theme_bw()
theme(axis.ticks = element_blank(),
legend.position = "left",
strip.placement = "outside",
strip.background = element_blank())
ggplotly(plotly.df)
但是,ggplotly似乎忽略space = "free"了facet_grid,因此單元格的大小不成比例:

有沒有辦法調整刻面寬度ggplotly?
非常感謝您提前
uj5u.com熱心網友回復:
您不必重新發明輪子。回到第一個ggplotly物件。域是 plotly 用來管理每個方面的空間(或在 plotly-subplot 中)。您可以通過將 ggplotly 圖分配給一個物件并呼叫plotly_json.
但是,我以前曾研究過布局快捷方式。您可以像這樣檢索和修改域:
p = ggplotly(plotly.df)
p$x$layout$xaxis$domain <- c(0, 1/2) # 6 blocks, 3 in this group 1/6 * 3
p$x$layout$xaxis2$domain <- c(1/2, 2/3) # start at previous position, 1 in this group
p$x$layout$xaxis3$domain <- c(2/3, 1) # remaining space
p$x$layout$yaxis3$domain <- c(0, 1/6) # 1 block in bottom chunks
p$x$layout$yaxis2$domain <- c(1/6, 2/3) # 3 in mid group
p$x$layout$yaxis$domain <- c(2/3, 1) # remaining space
p
這讓我走到了這一步:

您的底部標簽仍然對齊,但頂部沒有。此外,左下標簽被切斷。
為了修復頂部標簽,我曾經plotly_json弄清楚它們在哪里,然后使用了猜測和檢查方法。為了調整標簽,我修改了邊距。
# prevention
p$x$layout$annotations[[3]]$x <- 1/4
# diagnosis
p$x$layout$annotations[[4]]$x <- 7/12
p %>% layout(margin = list(t = 40, r = 50, b = 80, l = 130))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450735.html
標籤:r ggplot2 情节地 r-plotly ggplotly
上一篇:如何繪制圖并為每個圖指定特定名稱
下一篇:在一個資料框列中使用多個時區
