I'm sure there's a really easy way to do this but I can't for the life of me figure it out. I'm doing a scatter graph in Plot_ly.
Each point that I'm plotting has been assigned a label e.g. Pass, High, Low, Sigma high etc...
My problem is that I can't seem to fix what color plot_ly assigns to each label.
I want Pass to always be White, High to always be Green and so on, but it seems to randomly assign colors each time.
Here is the code I'm using to plot
library("plotly")
p <- plot_ly(PT,
type='scatter',
x=XAVG,
y=YAVG,
mode= "markers",
marker=list(size=3,bgcolor="#e5e5e5"),
color = label,
colors=c("yellow","red","cyan","magenta",'blue',"green3","white"),
zeroline=F,
text=paste("MEAS = ",PT$MEAS,"Head_ID = ",substr(PT$SHD_ID,2,5)))
Any help would be much appreciated as I've been stuck on this for ages!
Thanks!
You describe label
in your post but label
is missing from your data so I've added a label
column to PT
with some labels corresponding to colours as seem to be suggested in your comments. PT
is now:
SHD_ID MEAS XAVG YAVG PPKLOW PPKUP PKSLOW PKSUP colour label
1 1L3P1 0.300018 -5774.5 94350.5 FALSE FALSE TRUE FALSE blue Fail
2 1LSP0 0.300018 14245.5 94350.5 FALSE FALSE TRUE FALSE blue Fail
3 1L802 600.000000 -25024.5 94350.5 FALSE FALSE FALSE TRUE green3 Mean
4 ILSOl 0.300018 -5004.5 94350.5 FALSE FALSE TRUE FALSE blue Fail
5 1LSOO 0.300018 15015.5 94350.5 FALSE FALSE TRUE FALSE blue Fail
6 1LSN2 600.000000 -24254.5 94350.5 FALSE FALSE FALSE TRUE green3 Mean
The code first creates color_map
as a vector with named components to define the mapping between your labels and your colors. It then creates the plot assigning colors to the marker
property color
based on color_map
and label
. The label
values are also used to create a group
so that the assignment of color to labels is shown in the legend. I've made the markers larger just so the colors are easier to see.
#
# create a map between colors and labels
# colors ending in numbers are not recognized by plot_ly
#
color_map <- c(Pass="yellow", High="red", Low= "cyan",
Sigma= "magenta", Mean='limegreen', Fail="blue", Median="violet")
#
# plot points using color_map to assign colors by label
# show label colors in legend
#
p <- plot_ly(PT,
type='scatter',
x=XAVG,
y=YAVG,
mode= "markers",
marker=list(size=10, bgcolor="#e5e5e5",
color=color_map[label]),
group = label,
zeroline=FALSE,
text=paste("MEAS = ", MEAS,"Head_ID = ",substr(SHD_ID,2,5)))