简体   繁体   中英

x-axis labels ggplot2 in R

I am trying to label my individual boxplots in this graph as "Cong." and "Incong." I am drawing from a df "flanker.Summary.ID.RT", and using the column in this df "Type" for the boxplot x-axis, and the column "Flanker.RT" for the boxplot y-axis. I am currently trying this code:

flanker.A.1 <- ggplot() + 
  geom_line(data=flanker.Summary.ID.RT, aes(x=Type, y=Flanker.RT, group=ID),scale_x_discrete(labels=c("Cong.","Incong.")),
            color="gray")  +
  geom_point(data=flanker.Summary.ID.RT, aes(x=Type, y=Flanker.RT, group=ID), color="gray")  + 
  geom_boxplot(data=flanker.Summary.ID.RT, aes(x=Type, y=Flanker.RT),
               width=0.4, alpha=0.6, fill="#CEB888", outlier.colour = "gray") +
  theme_cowplot(font_size=24) +
  scale_x_discrete(name="Trial type") +
  scale_y_continuous(name="RT (ms)", limits=c(300, 630), breaks=c(300, 400, 500, 600)) +
  theme(panel.grid.major.y = element_line(colour="grey"))
flanker.A.1

As you can see, I am trying to use the scale_x_discrete to create labels, but the boxplot labels being produced from this code are drawing from the names in the "Type" and "Flanker.RT" columns in the original df instead. What am I doing wrong?

To relabel values on the x axis with scale_x_discrete() you need to access the labels argument. Here's a demonstration:

set.seed(1234)
x <- c(sample(LETTERS[1:3], 100, replace=TRUE))

p <- ggplot(as.data.frame(x), aes(x=x)) + geom_bar(aes(fill=x))
p

在此处输入图像描述

If you want to relabel the bars on the x axis, you use scale_x_discrete() and pass a vector to the labels argument. The name argument is the title of the axis. If you pass a normal vector to the labels argument, the order of the vector will be mapped according to the order of the x axis items. You can specify the mapping if you pass a named vector, like I show here:

p + scale_x_discrete(
  name="new axis name",
  labels=c("B" = "BBB", 'A'= 'AAA', 'C'= 'CCC')
)

在此处输入图像描述

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