![](/img/trans.png)
[英]How to build geom_tile/rect boxes with gradient fill and points/lines on top for factor x axis?
[英]Fill geom_tile with a gradient
我想創建一個漸變圖。 我想用漸變填充我的geom_tile
。 但是, R
經常告訴我Error: Discrete value supplied to continuous scale
。
df <- data.frame(value=c(55, 40, 5),
zz=c("A", "B", "C"))
df$lower <- df$value-2.9
df$upper <- df$value+2.9
ggplot(df, aes(x=zz, y=value, fill=zz))+
geom_tile(aes(x=zz, y=value, fill=zz), width=0.2,height=2.9)
現在,我想用漸變色(在中心最密集地着色(列=值),然后逐漸淡出到末端(上和下))為瓷磚着色。
我該如何實現? 是geom_tile
正確geom
這個? 謝謝
編輯
漸變應在圖塊內,請參見Alex Krusz的示例。 連結: 這里
我不認為ggplot適用於這種用途,但這是模擬透明度漸變的一種方法。
創建內插透明度值的數據集:
library(data.table)
df <- setDT(df)
n <- 100
df.lower <- df[, .(ymin = seq(lower, value, length.out = n + 1)[1:n],
ymax = seq(lower, value, length.out = n + 1)[2:(n+1)],
alpha = seq(0, 1, length.out = n)), by = .(zz)]
df.upper <- df[, .(ymin = seq(value, upper, length.out = n + 1)[1:n],
ymax = seq(value, upper, length.out = n + 1)[2:(n+1)],
alpha = seq(1, 0, length.out = n)), by = .(zz)]
df.new <- rbind(df.lower, df.upper)
df.new$x <- as.integer(df.new$zz)
df.new$xmin <- df.new$x - 0.2
df.new$xmax <- df.new$x + 0.2
> df.new
zz ymin ymax alpha x xmin xmax
1: A 52.100 52.129 0.00000000 1 0.8 1.2
2: A 52.129 52.158 0.01010101 1 0.8 1.2
3: A 52.158 52.187 0.02020202 1 0.8 1.2
4: A 52.187 52.216 0.03030303 1 0.8 1.2
5: A 52.216 52.245 0.04040404 1 0.8 1.2
---
596: C 7.755 7.784 0.04040404 3 2.8 3.2
597: C 7.784 7.813 0.03030303 3 2.8 3.2
598: C 7.813 7.842 0.02020202 3 2.8 3.2
599: C 7.842 7.871 0.01010101 3 2.8 3.2
600: C 7.871 7.900 0.00000000 3 2.8 3.2
繪制結果:
ggplot() +
geom_rect(data = df.new,
aes(xmin = xmin, xmax = xmax,
ymin = ymin, ymax = ymax,
alpha = alpha, fill = zz)) +
scale_x_continuous(breaks = as.integer(df$zz),
labels = df$zz) +
scale_alpha_identity() +
theme_bw()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.