I want to change the order of legend items in a state where the legend and plot colors are matched in ggplot2.

Asked 5 months ago, Updated 5 months ago, 14 views

If you search well, you may find a solution, but
I couldn't get there.
Professor, please.

R is trying to draw using tidyverse and qiime2R.


colpal<-c("red", "blue", "magenta", "deepskyblue", "maroon4", "darkgreen", "orange", "blueviolet", "honeydew4", "black", "salmon4")

  select(SampleID, PC1, PC2)%>%
  geom_point(alpha=0.7, size=3)+
  scale_shape_manual(values=c(16,17,15,18,18), name="Experimental priority-Sex")+
  scale_color_manual(values=colpal,name="Post inoculum day")+
  guides(shape=guide_legend(order=1), color=guide_legend(order=2))+
  ggtitle("Unweighted UniFrac")+
  theme(aspect.ratio=1,plot.title=element_text(size=20, face="bold"))

reference:Plotting PCoA

UniFrac PCoA

To order this color legend in days,

scale_color_manual(values=colpal, name="Post inoculum day", labels=c("1d", "2d", ..., "Origin_inoculum")+

If you add labels to the and scale_color_manual parts,
The number of days item names in the legend are in the desired order, but they do not match the plot color of the drawing.
(1d becomes red, 2d becomes blue...)

Where should I modify to match the plot and legend?

By the way, "Experimental priod-Sex" matches the three-dimensional description.

If you don't have enough additional information, please let us know in the comments.
I look forward to your kind cooperation.

macos r tidyverse ggplot2

2022-09-30 14:09

1 Answers

In the help values argument description

The values will be matched in order (usually alphabetic) with the limits of the scale, or with breaks if provided.

says .

If you set values, you must specify what the corresponding wks column value is. If not set, the correspondence may be wrong because it will be sorted in order. And labels is just to overwrite the legend label, not to specify the correspondence.

Therefore, specify the same breaks as specified in labels.

I think the reason the shape display is correct is because the order does not change even if it happens to be sorted.


g+scale_color_manual(values=c("red", "blue", "magenta"), labels=c("versicolor", "setosa", "virginica")))
g+scale_color_manual(values=c("red", "blue", "magenta"), breaks=c("versicolor", "setosa", "virginica"), labels=c("versicolor", "setosa", "virginica"))

Supplement: In addition to giving breaks, values, and labels, values can also be specified by giving values a named vector.

  values=c(versicolor="red", setosa="blue", virginica="magenta"),
  labels=c("versicolor", "setosa", "virginica"))


2022-09-30 14:09

If you have any answers or tips

© 2023 OneMinuteCode. All rights reserved.