Ответ 1
Итак, я не защищаю вас, полагаясь на ggplot
, чтобы сделать это, поскольку, скорее всего, некоторые из других предлагаемых решений лучше, но эта проблема заинтересовала меня, поскольку я имел в виду выкапывать кишки ggplot
на некоторое время. Это то, что мне удалось придумать:
ggplot(df, aes(x=x, y=y, length=length, width=width)) +
geom_hline(yintercept=seq(5, 35, by=10), color="white", size=2, linetype=2) +
geom_car() +
geom_text(aes(label=label, color=label), fontface=10, hjust=-0.2) +
coord_equal() +
theme(panel.background = element_rect(fill="#555555"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
Вам нужно будет найти стрелки, хотя я думаю, что это просто с geom_segment
. Теперь для этого нам нужно было создать geom_car
, хотя, если вам не нужны подробные изображения, вы можете просто использовать geom_rect
. Здесь geom_car
:
library(png)
library(ggplot2)
library(proto)
car.raster <- readPNG("data/car.png")
carGrob <- function(x, y, length, width) {
rasterGrob(
car.raster, x=x, y=y,
hjust=1, height=width, width=length
)
}
GeomCar <- proto(ggplot2:::Geom, {
draw <- function(., data, scales, coordinates, ...) {
with(
coord_transform(coordinates, data, scales),
carGrob(x, y, xmax-xmin, ymax-ymin)
)
}
draw_legend <- function(., data, ...) {
with(data, ggname(.$my_name(), fieldGrob(1, 0.5, )))
}
reparameterise <- function(., df, params) {
transform(df,
xmin = x - length / 2, xmax = x + length / 2, length = NULL,
ymin = y - width / 2, ymax = y + width / 2, width = NULL
)
}
objname <- "car" # name of the geom in lowercase. Must correspond to GeomField.
desc <- "A car!"
default_stat <- function(.) StatIdentity
required_aes <- c("x", "y")
guide_geom <- function(.) "car"
default_aes <- function(.) aes()
} )
geom_car <- function(mapping=NULL, data=NULL) {
GeomCar$new(mapping=mapping, data=data)
}
И сам автомобиль:
И данные, которые я использовал:
df <- read.table(h=T, t="vehicle x y length width label
1 150 10 14 5 other
2 180 8 12 5 other
3 220 10 18 5 other
4 145 20 15 5 target
5 250 18 14 5 other
6 160 30 13 5 other
7 200 33 15 5 other
8 240 31 22 5 other
")