我想提取與 ggplot 連續色標相關的中斷和顏色值。找到與每個日期點關聯的顏色有多種答案(像
我想獲得一個顯示中斷(12.5、15、17.5、20)和與它們相關的顏色值的資料框。
非常感謝!
uj5u.com熱心網友回復:
有兩種方法可以做到這一點,一種是構建情節,另一種是不構建情節。
如果我們建立情節;
library(ggplot2)
df <- data.frame(x = 1:10, y = 1:10, col = 11:20)
ggplot(df)
geom_point(aes(x = x, y = y, colour = col))

我們可以提取尺度并使用它來檢索相關資訊。
# Using build plot
build <- ggplot_build(last_plot())
scale <- build$plot$scales$get_scales("colour")
breaks <- scale$get_breaks()
colours <- scale$map(breaks)
data.frame(breaks = breaks, colours = colours)
#> breaks colours
#> 1 NA grey50
#> 2 12.5 #1D3F5E
#> 3 15.0 #2F638E
#> 4 17.5 #4289C1
#> 5 20.0 #56B1F7
或者,我們可以跳過構建圖并直接使用尺度本身,前提是我們通過向它展示資料的限制來“訓練”尺度。
scale <- scale_colour_continuous()
scale$train(range(df$col))
breaks <- scale$get_breaks()
colours <- scale$map(breaks)
data.frame(breaks = breaks, colours = colours)
如您所見,默認中斷演算法會產生越界中斷。如果您想稍后使用這些資訊,最好將其過濾掉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/487261.html
