I have a graph built like this

library(ggplot2) x <- sort(rnorm(1000)) y <- rnorm(1000) z <- rnorm(1000) + atan2(x, y) dt <- data.frame(x, y, z) g <- ggplot(dt, aes(x = x, y = y)) g <- g + geom_point(aes(color = z)) + scale_color_gradient(low="blue", high="red") plot(g) 

I want to add a table with a little statistics over the graph: total points, points with a value of z < -1 , points with values ​​of -1 <= z <= 1 , points with a value of z > 1 . I tried to add a table through annotation_custom() , but it turns out too crooked. Maybe there are some other ways to add a table above the graph?

    1 answer 1

    Made using the gridExtra library. Perhaps there is a simpler solution. If so, I will be glad if someone shares, while I bring my own.

    We count the number of points in the required intervals and collect the matrix

     all <- length(z) z1 <- length(z[z < -1]) z2 <- length(z[z >= - 1 & z <= 1]) z3 <- length(z[z > 1]) stat <- matrix(c(all, z1, z2, z3),ncol=4,byrow=TRUE) colnames(stat) <- c("Всего", "(...;-1)", "[-1; 1]", "(1; ...)") 

    Using tableGrob make a table

     table <- tableGrob(stat, rows = NULL) 

    We indicate how many parts on the canvas which graph will occupy, i.e. the table is 1/6, the chart is 5/6.

     lay <- rbind(c(1), c(2), c(2), c(2), c(2), c(2)) 

    We build the table and the schedule

     grid.arrange(table, g, layout_matrix = lay) 

    Result:

    Schedule

    • Here is a more nice version of stackoverflow.com/questions/40335838/… - Ogurtsov 5:56 pm
    • Yes, I tried to do this, the problem is that if there is a little empty space on the chart, then the table overlaps some of the points. Or you need to increase the area of ​​the graph. - Alexshev92