简体   繁体   中英

How to combine ggplot and plot?

I have tried:

ggplot(temp, aes(x,y)) + geom_hex(bins=100) + plot(y1,x1,pch = 0, col="red")

The image is without the second part(red points).What should I change?

> str(x)
 num [1:1397] 1.62 1.62 1.62 1.63 1.63 1.63 1.63 1.63 1.63 1.63 ...
> str(y)
 int [1:1397] 2998 3001 3005 2993 2998 2999 3002 3003 3004 3006 ...
> str(x2)
 num [1:6] 1.7 1.9 2.18 2.7 2.6 3
> str(y2)
 num [1:6] 3000 3600 4000 4800 5100 5600

The important point is that vectors length is not the same(1397 versus 6).

It works perfect.I have made data.frame from x2 and y2.

ggplot(temp, aes(x,y)) +
+   geom_hex(bins=100) +
+ geom_point(data=mk , aes(x=x2, y=y2), col = "red")

If you want to combine them in one plot, you can do everything in ggplot2 (supposing that x1 and y1 are in dataframe df ):

ggplot(temp, aes(x,y)) +
  geom_hex(bins=100) +
  geom_point(aes(x=x1, y=y1), data=df, shape=20, size=2, color="red")

It can be done using the package gridBase. I still prefer to use sp.plot than ggplot for plotting maps. So this feature might be useful. I should mention this page as the information that lead me to the answer.

A dummy example:

library(gridBase)
library(grid)
library(ggplot2)

data  <- data.frame(x=1:10,y=rnorm(10))

par(mfrow = c(1,2))

vp <- viewport(height = unit(1,"npc"), width=unit(0.5, "npc"), 
              just = c("left","top"),
              y = 0, x = 0)


print(plot(data$x,data$y,xlab="x",ylab="y",pch = 21,bg="black"),vp=vp)

vp <- viewport(height = unit(1,"npc"), width=unit(0.5, "npc"), 
              just = c("left","top"),
              y = 1, x = 0.5)


print(ggplot(data,aes(x,y)) + geom_point(),vp=vp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM