简体   繁体   中英

Is there an R function that colors blocks for a given vector of values?

I have a vector of 100 values, and I'd like to plot an intensity graph according to the values in a graph equally divided with 10 little squares.

I'm trying to use ggplot2 package in R, but I'm stuck. Below is my code

> vec <- rnorm(100,5,4) #100-vector

> ggplot(NULL)  + geom_vline(xintercept = 1:10) + geom_hline(yintercept = 1:10)+
  coord_cartesian(xlim = c(.45, 9.55), ylim = c(.45,9.553))+
  theme(legend.box.spacing = unit(0, "mm"),
        panel.background = element_blank(),
        panel.border = element_rect(colour = "black",fill=NA),
        axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())  #the graph with 100 blocks
[enter image description here][1]

I expect plot the colors in this graph according to the values to the "vec" variable, eg shades from red to smaller numbers, going dark blue to larger numbers.

I think this is more-or-less what you want. With ggplot , you need to plot data frames, not just random vectors. And we need to create columns to map to the x and y axes:

set.seed(47)
vec <- rnorm(100,5,4)
dd = expand.grid(x = 1:10, y = 1:10)
dd$vec = vec

ggplot(dd, aes(x = x, y = y, fill = vec)) +
  geom_tile() +
  scale_fill_gradient(low = "firebrick4", high = "dodgerblue2")

在此处输入图片说明

You might have better luck with other palettes, eg, scale_fill_distiller(palette = "Spectral") is pretty nice.

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