我只关注如何制作这张精确的图像,而不是是否有更好的可视化效果。
你做错的第一件事是你没有绘制地图
fill=
为了瓷砖什么都行。这就是为什么它是灰色的。
那么棘手的是,你不可能在
ggplot2
(我的理解是这是潜在的
grid
系统)。所以你需要对你的
tileData
对象,该对象实际上允许您绘制多个不同填充的矩形,以给人以单个渐变填充矩形的印象。
我想到的是:
library(ggplot2)
# set the seed so we all have the same data
set.seed(20180702)
# the data for the tiles of the plot
tileData <-
data.frame(
Factor = as.factor( rep(c("factor1", "factor2", "factor3") , each = 100)),
Height = c(seq(from = -2, to = 2, length.out = 100),
seq(from = -5, to = 5, length.out = 100),
seq(from = -3, to = 3, length.out = 100)),
Gradation = abs(seq(from = -1, to =1 , length.out = 100)))
)
# sample data we'll want to chart
exampleFrame <-
data.frame(
Period = as.factor(rep(c("first", "second", "third"), n = 3)),
Factor = as.factor(rep(c("factor1", "factor2", "factor3"), each = 3)),
Data = unlist(lapply(c(2, 5, 3),
function(height) rnorm(3, 0, height)))
)
# define the half-width of the rectangles
r <- 0.4
ggplot() +
# add the background first or it over-writes the lines
geom_rect(data = tileData,
mapping = aes(xmin = as.numeric(Factor) - r,
xmax = as.numeric(Factor) + r,
ymin = Height - 0.1,
ymax = Height + 0.1,
fill = Gradation)) +
# add the lines for each data point
geom_segment(data = exampleFrame,
aes(x = as.numeric(Factor) - r * 1.1,
xend = as.numeric(Factor) + r * 1.1,
y = Data, yend = Data,
col = Period),
size = 3) +
scale_fill_gradient2("Historic range\nof data", low = "white", high = "lightblue") +
scale_colour_manual(values = c("first" = "hotpink", "second" = "darkgreen", "third" = "darkblue")) +
scale_x_continuous("", breaks = unique(as.numeric(exampleFrame$Factor)), labels = levels(exampleFrame$Factor)) +
theme_minimal()