使用ggplot2

时间:2017-02-07 18:11:11

标签: r ggplot2

我最初尝试使用geom_rastergeom_tile来创建此背景,而是使用图像,因为我觉得它会更容易。

然而,我无法让图像占据整个背景,因此这些点正确地叠加在它上面。背景图片位于:http://imgur.com/a/eZGAP

应该如下所示: enter image description here

但它会像这样出现: enter image description here

以下是dput数据:

structure(list(Industry.Group = c("Defense / Military", "Energy", "Financial Services", "Healthcare", "Manufacturing", "Public Sector (non-defense) / Not For Profit", "Retail", "Services", "Technology", "Telecommunications", "Transportation" ), ciq_tech = c(55.9, 53.7111111111111, 60.743661971831, 45.0620689655172, 42.1529411764706, 52.2444444444444, 40.8, 52.3263157894737, 50.9222222222222, 59.5111111111111, 39.6666666666667), Industry.Group = c("Defense / Military", "Energy", "Financial Services", "Healthcare", "Manufacturing", "Public Sector (non-defense) / Not For Profit", "Retail", "Services", "Technology", "Telecommunications", "Transportation"), ciq_org = c(39.6666666666667, 48.7413636363636, 48.0868442622951, 42.2482222222222, 39.0128260869565, 38.482, 39.7786956521739, 41.7248387096774, 47.8644262295082, 49.6739285714286, 41.4825)), .Names = c("Industry.Group", "ciq_tech", "Industry.Group", "ciq_org"), row.names = c(NA, -11L), class = "data.frame")

我已经尝试了这一点并且一直在调整xminxmaxymin以及ymax变量:

library(png)
library(grid)
library(ggplot2)
img <- readPNG("grid.png") 
g <- rasterGrob(img, interpolate=TRUE) 

ggplot(both, aes(x = ciq_org, y = ciq_tech))  +
  theme_bw() + annotation_custom(g, xmin=31, xmax=57, ymin=38, ymax=61) + geom_point()

以及:

ggplot(both, aes(x = ciq_org, y = ciq_tech))  +
  theme_bw() + annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) + geom_point()

如果在ggplot2中使用固定的正方形和颜色重新创建背景,我也可以使用geom_raster

2 个答案:

答案 0 :(得分:4)

你可以试试这个:

ggplot(both, aes(x = ciq_org, y = ciq_tech))  +
  theme_bw() + annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) + 
  geom_point(size=5, col='steelblue') + 
  xlim(c(31, 57)) +
  ylim(c(38,61)) +
  theme_void()

enter image description here

答案 1 :(得分:3)

这是我正在研究的另一种解决方案:

img <- png::readPNG("KRWa02Q.png", info = TRUE)
dimensions <- attr(img, "info")$dim

 p <- ggplot(both, aes(x = ciq_org, y = ciq_tech))  +
        annotation_raster(img, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, interpolate = TRUE) +
        geom_point(size = 3) +
        theme(axis.ticks = element_blank(), axis.line = element_blank(), axis.title = element_blank(), axis.text = element_blank(),
              panel.grid = element_blank(), panel.border = element_blank(), panel.background = element_rect(fill = NA),
              aspect.ratio = dimensions[1]/dimensions[2],
              plot.margin = margin(0, 0, 0, 0, "in")) +
        scale_x_continuous(expand = c(0.15, 0.15)) +
        scale_y_continuous(expand = c(0.15, 0.15))

ggsave("tc.png", p, width = dimensions[1]/72, height = dimensions[2]/72, units = "in", dpi = 72)

Draft of image for tcash21