我有一个像这样的数据框
Hoehe 75 65 50 35 20 5
1 51.5 9.5 10.5 10.0 8.1 9.8 8.8
2 41.5 10.9 11.1 10.9 9.7 11.1 9.9
3 31.5 10.7 11.0 11.3 10.6 10.2 9.5
4 21.5 9.7 10.1 10.2 11.1 9.8 9.0
5 11.5 9.2 9.6 9.2 10.9 8.9 8.8
6 1.5 7.7 8.0 8.6 10.6 7.3 7.2
我想绘制二维插值图。 我重新调整了数据并使用 geom_raster 绘制了绘图。
library (ggplot2)
data_reshape <- data %>%
pivot_longer(
cols = `75`:`5`,
names_to = "Entfernung",
values_to = "value"
)
data_reshape$Entfernung = as.numeric(data_reshape$Entfernung)
ggplot(data_reshape, aes(Entfernung, Hoehe)) +
geom_raster(aes(fill = value), interpolate = TRUE) +
coord_cartesian(ylim = c(0, 58)) + #set lower and upper limits of your y-axis
scale_fill_gradient(low= "yellow", high ="red")
然而,在最终图中,看起来好像在 40 厘米处存在数据间隙。
有什么想法为什么会出现这个问题以及如何解决它吗?
问题是
geom_raster
适用于均匀分布的网格,其中用于绘制图块的宽度是根据网格点之间的最小宽度(在您的情况下为 10)设置的。然而,由于网格点间隔不均匀,最终会在点之间出现一些间隙,这些间隙比最小宽度更远。
解决这个问题的一个选项是填充网格,使其均匀分布,我使用
tidy::complete
并通过 zoo::na.approx
进行插值。
library(ggplot2)
library(tidyr)
library(dplyr, warn = FALSE)
data_reshape <- data %>%
pivot_longer(
cols = `75`:`5`,
names_to = "Entfernung",
values_to = "value"
)
data_reshape$Entfernung <- as.numeric(data_reshape$Entfernung)
data_reshape <- data_reshape |>
complete(Hoehe, Entfernung = full_seq(Entfernung, 5)) |>
mutate(
value = zoo::na.approx(value), .by = Hoehe
)
ggplot(data_reshape, aes(Entfernung, Hoehe)) +
geom_raster(aes(fill = value), interpolate = TRUE) +
scale_fill_gradient(low = "yellow", high = "red")
数据
data <- structure(list(
Hoehe = c(51.5, 41.5, 31.5, 21.5, 11.5, 1.5),
`75` = c(9.5, 10.9, 10.7, 9.7, 9.2, 7.7), `65` = c(
10.5,
11.1, 11, 10.1, 9.6, 8
), `50` = c(
10, 10.9, 11.3, 10.2, 9.2,
8.6
), `35` = c(8.1, 9.7, 10.6, 11.1, 10.9, 10.6), `20` = c(
9.8,
11.1, 10.2, 9.8, 8.9, 7.3
), `5` = c(
8.8, 9.9, 9.5, 9, 8.8,
7.2
)
), class = "data.frame", row.names = c(
"1", "2", "3",
"4", "5", "6"
))