Seyed Omid Nabavi
Seyed Omid Nabavi

Reputation: 497

How to increase the interval of labels in geom_text?

I am trying to put labels beside some points which are very close to each other on geographic coordinate. Of course, the problem is overlapping labels. I have used the following posts for reference:

The problem is that I do not want to relocate labels but increase the interval of labeling (for example every other 10 points).

I tried to make column as alpha in my dataframe to make unwanted points transparent

[![combined_df_c$alpha=rep(c(1,rep(0,times=11)),
                        times=length(combined_df_c$time)/
                          length(rep(c(1,rep(0,times=11)))))][1]][1]

I do not know why it does not affect the plot and all labels are plotted again.

The expected output is fewer labels on my plot.

[plot]

Upvotes: 2

Views: 455

Answers (1)

mischva11
mischva11

Reputation: 2956

You can do this by sequencing your dataframe for the labs of geom_text.

I used the build-in dataset mtcars for this, since you did not provide any data. With df[seq(1,nrow(df),6),] i slice the data with 6-steps. This are the labels which get shown in your graph afterwards. You could use this with any steps you want. The sliced dataframe is given to geom_text, so it does not use the original dataset anymore, just the sliced one. This way the amount of points for the labels and the amount of labels are equal.

df <- mtcars
labdf<- df[seq(1,nrow(df),6),]
ggplot()+
    geom_point(data=df, aes(x=drat, y=seq(1:length(drat))))+
    geom_text(data=labdf,
        aes(x=drat, y=seq(1:length(drat))), label=labdf$drat)

The output is as expected: from 32 rows, just 6 get labeled. plot

You can easily adjust the code for your case.


also: you can put the aes in ggplot() which may be more useful if you use more then just gemo_point. I made it like this, so i can clarify: there is a different dataset used on geom_text()

Upvotes: 1

Related Questions