简体   繁体   中英

Changing plotting order of points in R / ggplot2

I have the following code to plot a large dataset (450k) in ggplot2

x<-ggplot()+
  geom_point(data=data_Male,aes(x=a,y=b),color="Turquoise",position=position_jitter(w=0.2,h=1),alpha=0.1,size=.5,show.legend=TRUE)+
  geom_point(data=data_Female,aes(x=a,y=b),color="#FF9999",position=position_jitter(w=0.2,h=1),alpha=0.1,size=.5,show.legend=TRUE)+
  theme_bw()
x<-x+geom_smooth(data=data_Male,aes(x=a,y=b,alpha="Male"),method="lm",colour="Blue",linetype=1,se=T)+
  geom_smooth(data=data_Female,aes(x=a,y=b,alpha="Female"),method="lm",colour="Dark Red",linetype=5,se=T)+
  geom_smooth(data=data_All,aes(x=a,y=b,alpha="All"),method="lm",colour="Black",linetype=3,se=T)+
  scale_fill_discrete(name="Key",labels=c("Female","Male","All"))+
  scale_colour_discrete(name="Plot Colour",labels=c("Female","Male","All"))+
  scale_alpha_manual(name="Key",
                     values=c(1,1,1),
                     breaks=c("Female","Male","All"),
                     guide=guide_legend(override.aes=list(linetype=c(5,1,3),name="Key",
                                                          shape=c(16,16,NA),
                                                          color=c("Dark Red","Blue","Black"),
                                                          fill=c("#FF9999","Turquoise",NA))))

How can I change the order in which points are plotted? I have seen answered questions here dealing with a single dataframe but I am working with several dataframes so I cannot re-order the rows or ask ggplot to plot by certain criteria from within the dataframe. You can see an example of the kind of problem that this causes in the attached picture: the Female points are plotted on top of the Male points. Ideally I would like to be able to plot all the points in a random order, so that one "cloud" of points is not plotted on top of the other, obscuring it (NB the image shown doesn't include the "All" line).

Any help would be appreciated. Thank you.在此处输入图像描述

I belive this is not possible. The following should work though:

You'd have to paste the two data frames together to df . The new data frame will appear sorted by male and female.

You can then suffle the new data frame:

set.seed(42)
rows <- sample(nrow(df))
male_female_mixed <- df[rows, ]

Then you can plot male_female_mixed

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