简体   繁体   中英

Why does changing the label mess up my plot?

I have recently been playing around with various plot types using fictitious data to get my head around how I could display various pieces of information. One plot type that is gaining popularity is the so called individual differences dot plot which shows the change in each subjects score pre-post. The plot is fairly easy to produce, but my issue is that when I go to change the labels using either the labs or xlab ylab functions in ggplot , the plot itself becomes messed up. Below I have attached the fictitious data, the code used and the results.

Data

df<- data.frame(Participant<- c(rep(1:10,2)), Score<- c(rnorm(20,100,5)), Session<- c(1,1,1,1,1,1,1,1,1,1,                                                                                      2,2,2,2,2,2,2,2,2,2))
colnames(df) <- c("Participant", "Score", "Session")

Code for plot

p<- ggplot(df, aes(x=df$Session, y=df$Score, colour=df$Participant))+ geom_point()+
  geom_line(group=df$Participant)+ 
  theme_classic()

Plot Individual difference plot

My dilemma is that anytime I try to change the label names, the plot messes up as per below.

Problem

p + xlab("Session") + ylab("Score")

Plot after relabelling

The same thing happens if I try the labs function ie, p + labs(x= "Session", y= "Score") . You can see that the labels themselves do actually change, but for some reason this messes up the actual plot. Does any have any ideas as to what could be going wrong here?

The issue appears to be the grouping is undone when the label functions are called. Instead, issue the grouping as an aesthetic mapping:

library(dplyr); library(ggplot)

df %>% mutate(across(c(Session,Participant),factor)) -> df

p <- ggplot(df, aes(x=Session, y=Score, colour=Participant))+ geom_point()+
  geom_line(aes(group=Participant))+ 
  theme_classic() 

p + xlab("Session") + ylab("Score")

在此处输入图像描述

I suspect this is probably a bug.

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