How to fix the position of the geom_text label so that it is always in the middle of the site?

I would like to create a function that creates a ggplot graph.

data1 <- data.table(x=1:5, y=1:5, z=c(1,2,1,2,1))
data2 <- data.table(x=1:5, y=11:15, z=c(1,2,1,2,1))

myfun <- function(data){
    ggplot(data, aes(x=x, y=y)) +
        geom_point() +
        geom_text(aes(label=y), y=3) +
        facet_grid(z~.)
}

myfun(data2)

It is supposed to indicate the text on the chart. However, without knowing the data in advance, I cannot manually adjust the position of the text vertically. Especially I don’t want the label to move positions with data: I want it to always be about 1/4 vertical from the plots. (Upper middle)

How can i do this?

Is there a function that returns y.limit.upand y.limit.bottomthen I can assign y = (y.limit.up + y.limit.bottm) / 2or something else.

+4
source share
3 answers

x y geom_text(...) . @agstudy , y . , ( max min ..) ggplot , , (. ).

, , .

data1 <- data.table(x=1:5, y=1:5, z=c(1,2,1,2,1))
data2 <- data.table(x=1:5, y=11:15, z=c(1,2,1,2,1))

myfun <- function(data){
    label.pos <- data[,ypos:=min(y)+0.75*diff(range(y)),by=z] # 75% to the top...

    ggplot(data, aes(x=x, y=y)) +
        geom_point() +
    #   geom_text(aes(label=y), y=3) +
        geom_text(data=label.pos, aes(y=ypos, label=y)) +
        facet_grid(z~., scales="free")     # note scales = "free"
}

myfun(data2)

.

enter image description here

, = "", @agstudy - .

+5

, :

ggplot(data2, aes(x=x)) +
        geom_point(aes(y=y)) +
        geom_text(aes(label=y, y=mean(range(y)))) +
        facet_grid(z~.)

y :

scale_y_continuous(limits = c(10, 15))
+4

@ user890739: with geom_density you can evaluate the ypos variable like this:

data<-dplyr::mutate(group_by(data, z), ypos=max(density(y)$y)*.75*nrow(data))

Then draw the result:

ggplot(data, aes(x=x)) +
    stat_density(aes(y=..density..)) +
    geom_text(aes(label=y, y=ypos)) +
    facet_grid(z~., scales="free")
0
source

All Articles