简体   繁体   中英

ggPlot2 legend adjustment

I am plotting scatterplot using ggplot for 10 subjects and each subject contain 2 values in two different columns. I am able to plot scatter plot but not been able to adjust legend for it. Legend box should show donor-1, donor-2..., donor-10, but instead it is showing donor-1, donor-10, ...., donor-9. Also, it is showing block of size mentioned in geom_point function in legend which should not be there.

Below is my code snippet for it:

color1 = 'red'
color2 = 'green'
color3 = 'blue'
color4 = 'forestgreen'
color5 = 'purple'
color6 = 'yellow'
color7 = 'orange'
color8 = 'royalblue'
color9 = 'palevioletred4'
color10 = 'pink'

 p2<-qplot(CEACAM4.2hrs, CEACAM4.EDTA, data=res, xlab="CECAM4   PAX 2 Hr", ylab=" CECAM4 EDTA 0 Hr")


 p3<-p2+geom_point(aes(color = row.names(res2), size = 3))  + scale_x_continuous(limit =c(22,28), breaks = c(22,23,24,25,26,27,28)) + scale_y_continuous(limit=c(22,28), breaks = c(22,23,24,25,26,27,28)) +  stat_smooth(method="lm", se=FALSE)+ scale_color_manual(values=c(color1, color2, color3, color4, color5, color6, color7, color8, color9, color10))

 p4<- p3 + guides(colour = guide_legend(override.aes = list(size = 10)))

 p4+ ggtitle("CECAM4 EDTA 0Hr Vs PAX 2Hr") +  theme(plot.title = element_text(size = 28,colour=" mediumvioletred", face = "bold"))+ theme(legend.key = element_rect(colour = "black"), legend.title=element_text(size=22), legend.text=element_text(size=20)) + theme(plot.margin=unit(c(2.5,2,2,2),"cm"))+ theme(axis.text=element_text(size=18, face="bold"), axis.title=element_text(size=20, face="bold", colour="purple4")) + theme(axis.title.y=element_text(vjust=-0.65)) + theme(axis.title.x=element_text(vjust=-3.0)) + theme(plot.title = element_text(vjust=5)) + theme(axis.ticks.length=unit(1,"cm")) + theme(legend.key.size=unit(1.5,"cm"))

 ggsave(file="ggplot_cecam4_2_edta.png")

So, question more precisely is, how can I get legend in sequence with ggplot? eg

Donor-1

Donor-2

Donor-3

Donor-4

Donor-5

Donor-6

Donor-7

Donor-8

Donor-9

Donor-10

Thank you..

You did't provide data to test your code... For what I see the legend is produced on

color = row.names(res2)

So I guess row.names contains Donor-1, Donor-2, etc. They are character, so try to make them factor

color = factor(row.names(res2), levels=c("Donor-1", "Donor-2", etc.))

( factor enables custom order on vectors)

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