简体   繁体   中英

Multi-row labels in ggplot2

I have a plot which contains multiple entries of the same items along the x-axis. I have a total of 45 items grouped according to the groups below.

  pvalall$Group<-c(rep("Physical",5*162),rep("Perinatal",11*162),rep("Developmental",3*162),
                   rep("Lifestyle-Life Events",5*162),rep("Parental-Family",13*162),rep("School",3*162),
                   rep("Neighborhood",5*162))
pvalall$Group <- factor(pvalall$Group,
                        levels = c("Physical", "Perinatal", "Developmental", 
                                     "Lifestyle-Life Events", "Parental-Family",
                                    "School","Neighborhood"))

在此处输入图像描述

So essentially there are 162*45=7290 points along the x-axis and each 162 set of them corresponds to one of the variables of interest. How do I get geom_point to only plot one lable for each of these 162 given a list of the variable names c("var1","var2",....,"var45") ?

A reprex would be nice, but generally the solution is to create a separate dataframe with one row per group indicating where the labels should go, and to add a geom_text() layer to your plot that uses this dataframe.

My guess is that the code should look like this:

# create a dataframe for the labels
pvalall %>% 
  group_by(Group) %>% 
  summarize(Domains = mean(Domains),
            `-log10(P-Values)` = mean(`-log10(P-Values)`)) -> label_df

# now make the plot 
pvalall %>% 
  ggplot(aes(x = Domains, y = `-log10(P-Values)`)) + 
  geom_point(aes(col = Group)) +  # putting col aesthetic in here so that the labels are not colored
  geom_text(data =label_df, aes(label = Group))

Here is an example with mtcars :

library(tidyverse)
mtcars %>% 
  group_by(cyl) %>% 
  summarize(mpg = mean(mpg),
            disp = mean(disp)) %>% 
  mutate(cyl_label = str_c(cyl, "\ncylinders")) -> label_df

mtcars %>% 
  ggplot(aes(x = mpg, y = disp)) + 
  geom_point(aes(col = factor(cyl)), show.legend = F) + 
  geom_text(data = label_df, aes(label = cyl_label)) 

produces在此处输入图像描述

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