使用 ggplot 未完全填充等高线图
Contour plot is not been filled completely using ggplot
我正在尝试使用 ggplot
绘制我的第一个填充等高线图。使用我的数据,我正在观察类似的东西:
但我的结果是:
a <- c(1, 1.1, 1, 1.3, 1.2, 2, 2.2, 2, 2.5, 2.1, 3, 3, 3, 3.1, 3.2)
b <- c(rep(c(0, 5, 10, 15, 20), 3))
c <- seq(0, 1000, by = 1000/14)
DF <- data.frame(a, b, c)
ggplot(DF, aes(x = a, y = b, z = c)) +
geom_raster(aes(fill = c)) +
geom_contour() + scale_fill_gradientn(colours = rainbow(10))
我哪里做错了,在哪里可以找到有关此图的更多数据信息?
这是一个例子:
生成坐标:
b = c(0, 5, 10, 15, 20)
a = (1:30)/10
生成所有坐标组合
df <- expand.grid(a, b)
通过 a 和 b+1 的 tcrossprod 生成 c(这完全是任意的,但会生成一个很好的模式)
df$c <- as.vector(a %o% (b+1))
ggplot(df, aes(x = Var1, y = Var2, z = c, fill = c)) +
geom_raster(interpolate = T) + #interpolate for success
scale_fill_gradientn(colours = rainbow(10))
通常,如果您有一个值矩阵(z 值)要在 ggplot 中绘制,您需要通过 reshape2
中的 melt
将其转换为长格式或收集 tidyr
然后用于绘图。
您的数据非常稀疏,解决此问题的一种方法是生成缺失数据。我将展示如何使用 loess 函数完成:
model <- loess(c ~ a + b, data = DF) #make a loess model based on the data provided (data in OP)
z <- predict(model, newdata = expand.grid(a = (10:30)/10, b = (0:200)/10)) #predict on the grid data
df <- data.frame(expand.grid(a = (10:30)/10, b = (0:200)/10), c = as.vector(z)) #append z to grid data
ggplot(df, aes(x = a, y = b, z = c, fill = c)) +
geom_raster(interpolate = T)+
scale_fill_gradientn(colours = rainbow(10))
我正在尝试使用 ggplot
绘制我的第一个填充等高线图。使用我的数据,我正在观察类似的东西:
但我的结果是:
a <- c(1, 1.1, 1, 1.3, 1.2, 2, 2.2, 2, 2.5, 2.1, 3, 3, 3, 3.1, 3.2)
b <- c(rep(c(0, 5, 10, 15, 20), 3))
c <- seq(0, 1000, by = 1000/14)
DF <- data.frame(a, b, c)
ggplot(DF, aes(x = a, y = b, z = c)) +
geom_raster(aes(fill = c)) +
geom_contour() + scale_fill_gradientn(colours = rainbow(10))
我哪里做错了,在哪里可以找到有关此图的更多数据信息?
这是一个例子:
生成坐标:
b = c(0, 5, 10, 15, 20)
a = (1:30)/10
生成所有坐标组合
df <- expand.grid(a, b)
通过 a 和 b+1 的 tcrossprod 生成 c(这完全是任意的,但会生成一个很好的模式)
df$c <- as.vector(a %o% (b+1))
ggplot(df, aes(x = Var1, y = Var2, z = c, fill = c)) +
geom_raster(interpolate = T) + #interpolate for success
scale_fill_gradientn(colours = rainbow(10))
通常,如果您有一个值矩阵(z 值)要在 ggplot 中绘制,您需要通过 reshape2
中的 melt
将其转换为长格式或收集 tidyr
然后用于绘图。
您的数据非常稀疏,解决此问题的一种方法是生成缺失数据。我将展示如何使用 loess 函数完成:
model <- loess(c ~ a + b, data = DF) #make a loess model based on the data provided (data in OP)
z <- predict(model, newdata = expand.grid(a = (10:30)/10, b = (0:200)/10)) #predict on the grid data
df <- data.frame(expand.grid(a = (10:30)/10, b = (0:200)/10), c = as.vector(z)) #append z to grid data
ggplot(df, aes(x = a, y = b, z = c, fill = c)) +
geom_raster(interpolate = T)+
scale_fill_gradientn(colours = rainbow(10))