誰能幫我把下面的基礎R代碼翻譯成ggplot2:
編輯--我的x值是觀測值。
編輯 - 我的X值是觀察值。例如:
x < -runif(100。 min=0。 max=60)
lim_x <-range(x)
lim_y <-c(0. 5,3.5)
概率< -cbind(seq(from=0。 to=1,/span>length. out=100),。
c(seq(from=0。 to=1,length。 out=50)。 seq(from=1。 to=0,length。 out=50)),.
seq(from=1。 to=0,length。 out=100))
plot(c(lim_x[1]/span>。 lim_x[2])。 c(lim_y[1]/span>。 lim_y[2])。 型別= "n"。 ylab=""。 xlab="")
for(i in 1。 ncol(probabilities)){
p <-概率[,i] /span>
梯度。 rect(lim_x[1], i-0。 5,lim_x[/span>2]。 i 0。 5,nslices=nrow(probabilities),
紅色=1。 綠色=1-p。 blues=1-p)
}
這就產生了這個情節:
uj5u.com熱心網友回復:
這就是我如何將基礎R代碼翻譯成ggplot2:
library(ggplot2)
lim_x < -c(0,60)
lim_y <-c(/span>0. 5,3.5)
概率< -cbind(seq(from=0。 to=1,/span>length. out=100),。
c(seq(from=0。 to=1,length。 out=50)。 seq(from=1。 to=0,length。 out=50)),.
seq(from=1。 to=0,length。 out=100))。
df <- reshape2::melt(probabilities)
ggplot(df, aes(Var1, Var2, 填充=值))
geom_tile()
scale_fill_gradientn(colours = c("white"/span>。 "red")
注釋("rect"/span>。 xmin = min(df$) operator">$Var1) - 0. 5, xmax = max(df$) operator">$Var1) 0. 5,
ymin = unique(df$Var2) - 0. 5, ymax = unique(df$) operator">$Var2) 0. 5,
color = "black", fill = NA)

創建于2021-09-14,由reprex包(v2.0.1)創建
。另外,如果你想要完全相同的顏色,你可以使用:
ggplot(df, aes(Var1,Var2))
geom_tile(aes(fill = I(rgb(1。 1 - value。 1 - value))))
注釋("rect"/span>。 xmin = min(df$) operator">$Var1) - 0. 5, xmax = max(df$) operator">$Var1) 0. 5,
ymin = unique(df$Var2) - 0. 5, ymax = unique(df$) operator">$Var2) 0. 5,
color = "black", fill = NA)
uj5u.com熱心網友回復:
你必須要轉換你的資料
probabilities_long < -矩陣(t(probabilities)。 ncol = 1)。
df <- data. frame(x1 = sort(rep(seq(0。 60, length. out = 100)。 3)),
x2 = sort(rep(seq(0。 6, 60. 6,長度。 out = 100)。 3)),
y1 = rep(c(0. 5, 1. 5, 2. 5),100),
y2 = rep(c(1. 5, 2. 5, 3. 5),100),
prob = matrix(t(probabilities)。 ncol = 1))
然后你可以使用geom_rect來繪制每塊瓷磚:
ggplot(df)
geom_rect(Aes(xmin=x1, xmax=x2, ymin=y1。 ymax=y2。 填充= prob))
scale_fill_gradient(low = "#ffffff",
高 = "#ff0000")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/318918.html
標籤:

