Mapping values by specific color

ggplot2
plotly

#1

I want to create plots with various variables and groupings. For eg under type section I have vegetables, fruits and in another dropdown its listed with squash,onions,etc for vegetables and apple,bananas for fruits. My question here is if am doing a bar chart or line chart the color for apple should alway be red and color for avocado should be green. How can I set these colors specifically.
Thank you.


#2

Check out scale_color_manual from ggplot2. For example, you might do:

... # ggplot object making
  + scale_color_manual(values = c(apple = "red", avocado = "green", ...))

#3

I agree with @nwerth that making a named vector for the color scale is probably the way to go.

Here are some related answers from Stack Overflow that go into more detail:



#4

Thank you.Would there be anything similar for plotly as well. I couldnt find custom/manual color options with plotly.


#5

I'm not super familiar with the default plotly interface, but it also has a ggplotly function that turns ggplots into plotly ones! I'm about 90% sure that it'll respect scale_colour_manual and scale_fill_manual.


#6

For plotly bar charts, there are several examples starting here (scroll down for more):

There is a similar gallery of examples for other types of charts, as well as the full plotly function reference where you can find information on things such as creating your own colorscale (similar to ggplot’s scale_color_manual).

But I agree, if you’ve already got your plot working with ggplot() and you are struggling with plotly’s documentation, ggplotly seems like the way to go.


#7

The plot_ly() analogy for ggplot2::scale_color_manual() is to supply a named character vector to colors like this:

library(plotly)

d <- data.frame(
  fruit = c("Apple", "Avocado"),
  yummyness = c(1, 5),
  color = c("red", "green"),
  stringsAsFactors = FALSE
)

plot_ly(d,
  x = ~fruit,
  y = ~yummyness,
  color = ~fruit,
  colors = ~setNames(color, fruit)
) %>%
  add_bars()