问题描述
我正在尝试使用 ggplot
绘制我的第一个填充轮廓图。根据我的数据,我正在选择类似的内容:
I'm trying to do my first ever filled contour plot using ggplot
. With my data, I was specting something like:
但是我的结果是:
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))
我做错了什么,在哪里可以找到有关该图的更多数据化信息?
What I'm doing wrong, and where I can find more datailed information about this plots?
推荐答案
以下是示例:
生成坐标:
b = c(0, 5, 10, 15, 20)
a = (1:30)/10
生成所有坐标组合
df <- expand.grid(a, b)
通过a和b + 1的tcrossprod生成c(这是完全任意的,但会生成一个不错的模式)
generate c via tcrossprod of a and b+1 (this is completely arbitrary but will generate a nice pattern)
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))
通常,如果您有要在ggplot中绘制的值矩阵(z值),您需要通过 reshape2
melt 将其转换为长格式>或盖特,然后使用它进行绘图。
generally if you have a matrix of values (z values) to be plotted in ggplot you will need to convert it to long format via melt
in reshape2
or gather in tidyr
and then use for plotting.
您的数据非常稀疏,一种解决方法是生成丢失的数据。我将展示如何用黄土函数来完成:
Your data is very sparse, one approach to overcome this is to generate the missing data. I will show how to accomplish with loess function:
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完全填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!