问题
I am trying to plot my scatter points in plotly, each with a specified color by category.
It works fine until I start to use "split" (this line of code shows the legend) and should, by description "split" the categorial variable up, into different categories.
This is a reproducible example:
# Load data
df_soccer <- data.frame("x" = 1:4,
"y" = 2:5,
"Name" = c("Manchester United", "FC Barcelona", "FC Porto", "Borussia Dortmund"),
"soc_color" = c("rgb(218, 2, 14)","rgb(167, 0, 66)", "rgb(0, 147, 51)", "rgb(0, 0, 0)"))
# Use plot_ly to plot it
df_soccer %>%
plot_ly() %>%
add_trace(.,
x = ~x,
y = ~y,
type = "scatter",
hoverinfo = "text",
text = paste(df_soccer$Name),
# split = df_soccer$Name,
mode = "markers",
marker = list(color = ~soc_color, size = 20))
What I expected is this plot:
As you can see the colours are mixed up. Borussia Dortmund should be black and ManU should be red. This is what I want, solely the legend is missing:
Does anyone has some advices to get the colours right with splitting them by category and plot them in the right colour?
Much thanks in advance!
回答1:
By using Ben's suggestion and converting the "Name" variable into factors of the proper order the colors and the Names now match.
library(plotly)
# Load data
df_soccer <- data.frame(x = 1:4,
y = 2:5,
Name = c("Manchester United", "FC Barcelona", "FC Porto", "Borussia Dortmund"),
soc_color = c("rgb(218, 2, 14)","rgb(167, 0, 66)", "rgb(0, 147, 51)", "rgb(0, 0, 0)"), stringsAsFactors = FALSE)
df_soccer$Name<-factor(df_soccer$Name, levels=c("Manchester United", "FC Barcelona", "FC Porto", "Borussia Dortmund"))
plot_ly(df_soccer, name=~Name) %>%
add_trace(x = ~x,
y = ~y,
type = "scatter",
mode= "markers",
marker=list(color=~soc_color, size = 20))
To answer your question with added a duplicate value to the table. The easiest way for me to get it to work was to build the chart with ggplot2 and then convert it to a Plotly object.
library(ggplot2)
df_soccer <- data.frame("x" = 1:4,
"y" = 2:5,
"Name" = c("Manchester United", "FC Barcelona", "FC Porto", "Borussia Dortmund"),
"soc_color" = c("red","dark red", "green", "black"))
df_soccer <-rbind(df_soccer[1:2,], df_soccer[1,], df_soccer[3:4,])
df_soccer$y[3]<-3.5
g<-ggplot(df_soccer, aes(x=x, y=y, color=soc_color, name=Name)) +
geom_point( size=5) +
scale_colour_identity(guide = "legend", labels=(df_soccer$Name), breaks=(df_soccer$soc_color))
ggplotly(g)
来源:https://stackoverflow.com/questions/57824941/split-up-by-category-in-plotly