我想顯示被覆寫的范圍(包括重疊),(在使用堆疊條形圖的一些失敗后)我選擇了geom_rect。下面的代碼對一種型別來說很有效。
library(tidyverse)
#創建假資料
foo < - tibble(start = c(1。 150。 140, 75。 300),
端 = c(150。 180。 170, 160。 400))
ggplot()
geom_rect(data = foo, aes(xmin = start, xmax = end, ymin = 0。 ymax = 1)。 填充= "green"。 linetype = "blank", Alpha = 0. 3)
geom_rect(data = foo。 aes(xmin = 1。 xmax = max(end)。 ymin = 0。 ymax = 1)。 填充= NA。 顏色 = "black")
scale_y_continuous(name = ""。 打破= NULL。 限制 = c(0, 1))
scale_x_continuous(name = ""。 斷裂= NULL)
theme_minimal()
主題(panel.grid = element_blank())
如果我像下面那樣添加更多的資料(只有一種型別,但在原始資料中我確實還有一些),我可以 "手工 "添加資料,即為每種型別添加兩行代碼,但我正在尋找一種通過分組來實作的方法,但沒有成功。
foo <- foo %>%
mutate(type = "A", . before = 1) 。
bar <- tibble(type = "B",
開始 = c(1。 30, 40。 100, 150。 200, 310),
端 = c(20。 50, 100。 120, 200。 300, 380))
foo <- bind_rows(foo, bar)
ggplot()
geom_rect(data = foo %> %過濾器(type == "A")。 aes(xmin = start, xmax = end, ymin = 0, ymax = 1)。 填充= "green"。 linetype = "blank", Alpha = 0. 3)
geom_rect(data = foo。 aes(xmin = 1。 xmax = max(end)。 ymin = 0。 ymax = 1)。 填充= NA。 color = "black")
geom_rect(data = foo %> %過濾器(type == "B")。 aes(xmin = start, xmax = end, ymin = 2, ymax = 3)。 填充= "green"。 linetype = "blank", Alpha = 0. 3)
geom_rect(data = foo。 aes(xmin = 1。 xmax = max(end)。 ymin = 2。 ymax = 3)。 填充= NA。 顏色 = "black")
scale_y_continuous(name = ""。 打破= NULL。 限制 = c(0, 3))
scale_x_continuous(name = ""。 打破= NULL)
geom_text(aes(x = c(0。 0)。 y = c(0。 5, 2. 5)。 標簽 = c("A"/span>。 "B"))。 大小= 4。 hjust = 2)
theme_minimal()
主題(panel.grid = element_blank())
因此,圖表已經看起來是我想要的樣子,但我更希望通過使用分組(或任何其他非手動的方式)來達到這個目的。
也許還有一種不同的幾何或方法來獲得這種圖形?
uj5u.com熱心網友回復:
你可以寫一個小的輔助函式,在連續空間中定位一個分類的值。下面的例子。
helper < - function(x) {(match(x, 排序(unique(x))) - 1) * 2}
ggplot(foo)
geom_rect()
aes(xmin = start, xmax = end,)
ymin = helper(type),
ymax = helper(type) 運算子"> 1)。
填充 = "green"。 linetype = "blank", Alpha = 0. 3
)
geom_rect()
aes(xmin = min(start)。 xmax = max(end),
ymin = helper(type),
ymax = helper(type) 運算子"> 1)。
填充 = NA, 顏色 = "black"
)
scale_y_continuous(name = ""。 打破= NULL。 限制 = c(0, 3))
scale_x_continuous(name = ""。 休息= NULL)
注釋()
"text"。 x = c(0。 0)。 y = c(0。 5, 2. 5)。 標簽 = c("A"/span>。 "B"),
size = 4, hjust = 2
)
theme_minimal()
主題(panel.grid = element_blank())

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/318886.html
標籤:
上一篇:無法連接到外部IP
下一篇:ggplot總結boxplot

