我想為斷點顯示帶有自定義標簽的離散比例,并包含帶有自定義標簽的限制。我知道在顯示限制內的中斷時有效的代碼,但是當限制處于活動狀態時,標簽不再適用于這種方法
這是有效的方法:
library(ggplot2)
ggplot(mpg, aes(cty, hwy, color = year))
geom_point()
scale_color_binned(limits = c(1999, 2008),
breaks = c(2000, 2002, 2004, 2006),
labels = c('2', '3', '4', '5'),
show.limits = F) # proof that this method works for breaks WITHIN limits
當為此圖激活限制時,ggplot 會給出錯誤訊息并且不渲染圖
library(ggplot2)
ggplot(mpg, aes(cty, hwy, color = year))
geom_point()
scale_color_binned(limits = c(1999, 2008),
breaks = c(2000, 2002, 2004, 2006),
labels = c('2', '3', '4', '5'),
show.limits = T) # method fails when limits are activated
錯誤
f():!中斷和標簽的長度不同
中斷和標簽顯然是相同的長度。也許一些關于激活限制的東西會改變標簽向量的形成方式?我知道在哪里可以找到 ggplot2 中斷向量的代碼(使用ggplot_build()或直接單擊保存的繪圖物件)。我瀏覽了這些內容,沒有發現任何可以幫助我理解如何解決這個問題的東西。
我也嘗試了這些方法,它回傳了相同的錯誤“中斷和標簽長度不同”:
# this did not work
ggplot(mpg, aes(cty, hwy, color = year))
geom_point()
scale_color_binned(limits = c(1999, 2008),
breaks = c(2000, 2002, 2004, 2006),
labels = c('1', '2', '3', '4', '5', '6')
show.limits = T) # added more entries to label vector did not work
# this also did not work
ggplot(mpg, aes(cty, hwy, color = year))
geom_point()
scale_x_continuous(
breaks = c(0, 20, 40),
labels = c("0", "20", "40"))
scale_color_binned(breaks = c(1999, 2000, 2002, 2004, 2006, 2008),
labels = c('1', '2', '3', '4', '5', '6'),
show.limits = F) # add limits directly to breaks did not work
下面寫了一種可用于標記每個條目的方法。但是,如果離散量表有多個條目,則此方法很繁瑣。
ggplot(mpg, aes(cty, hwy, color = year))
geom_point()
scale_color_binned(limits = c('1' = 1999, '6' = 2008),
breaks = c('2' = 2000, '3' = 2002, '4' = 2004, '5' = 2006),
show.limits = T) # this works, but is a tedious solution when writing several breaks
我想使用 scale_color_binned 方法(或類似函式),因為我想將連續比例??資料轉換為 15-20 個離散范圍,然后自定義標簽或抑制不同范圍的標簽。
有沒有一種方法可以生成一個 ggplot ,它可以接受分箱連續值的自定義標簽,同時還顯示資料的指定限制?
uj5u.com熱心網友回復:
如果你使用一個函式來標記中斷,你就會知道發生了什么:
library(ggplot2)
ggplot(mpg, aes(cty, hwy, color = year))
geom_point()
scale_color_binned(limits = c(1999, 2008),
breaks = c(2000, 2002, 2004, 2006),
labels = ~ print(.x),
show.limits = TRUE)
#> [1] 2000 2002 2004 2006
#> [1] 1999 2008
您可以看到中斷標簽和限制標簽分兩批發送到標簽函式,因此固定長度的標簽向量對于這些批次中的一個或其他批次總是會失敗。確實,您需要一個可以處理以下任一項的函式:
ggplot(mpg, aes(cty, hwy, color = year))
geom_point()
scale_color_binned(limits = c(1999, 2008),
breaks = c(2000, 2002, 2004, 2006),
labels = ~ if(length(.x) == 2) .x else 1:4,
show.limits = TRUE)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462722.html
上一篇:如何在ggplot2R中為多面資料指定多個xlim?
下一篇:組合多個直方圖ggplot
