Home>

I need to build a graph that will colorize my data with the appropriate colors. The data are numbered in order and every 64 samples the color of these samples should change. I got the chart I needed.

Now I need to create a legend for this graph, where in the title "a= " and it says that red (for 1..64 samples) corresponds to a=0.25, green (for 65..128) corresponds to a=0.5 , yellow -a=0.75, blue -a= 1.

Code for the already created chart:

col <-with(mds.data, ifelse(mds.data.Sample<65, "red3",
                         ifelse(mds.data.Sample>=65 &
 mds.data.Sample<129 forest green
                                ifelse(mds.data.Sample>=129 &
 mds.data.Sample<193, "dark blue", "orange"))))
ggplot(data=mds.data, aes(x=X, y=Y, label=Sample)) +
  geom_text(show.legend= TRUE,col=col) +
  theme_bw() +
  xlab(paste("PCoA1 -", mds.var.per[1], "%", sep="")) +
  ylab(paste("PCoA2 -", mds.var.per[2], "%", sep="")) +
  ggtitle("PCoA plot using dtw-distance")+
  scale_color_discrete(name="a=",labels=c("0.25", "0.5","0.75","1"))

The legend is not being created for some reason. I have tried other methods besidesscale_color_discrete, but the desired legend is not created :(

I will listen to any suggestions on how to create the correct legend for my chart.

  • Answer # 1

    We need to make a common dataframe for all data, incl. add col. Then it will work with minimal edits

    ggplot(data=mds.data, aes(x=X, y=Y, col=col)) +
      geom_text(aes(label=Sample), fill= legend) +
      etc.
    

    The legend appeared, but in this case the colors were not the ones that were specified, and at the same time they do not correspond to the desired values ​​of the parameter a. That is, for example, the values ​​of samples 1..64 according to the arranged colors correspond to a=1, and should correspond to a=0.25.

    Диана2022-02-12 20:42:12