notthisone
notthisone

Reputation: 21

Display NA values with plotly

Let's say I have a data.table like the following

data = data.table(week=c(1,2,3),price=c(2,2.5,1.5),promotion=c("p1",NA,"p2"))

week, price, promotion w1, 2, p1 w2, 2.5, NA w3, 1.5, p2

I want to display a scattered plot of the price with the different promotion colored.

plot_ly(d, x = ~week, y = ~price,color=~promotion)

The problem is, the output I have doesn't show the the second observation because of the NA value in the column promotion as shown below.

plotly output I want to display all prices including the ones with NA in column "promotion" Thank you for your help!

Upvotes: 1

Views: 4317

Answers (2)

Shree
Shree

Reputation: 11150

Just extending on Pork Chop's solution and your comment under it. Here's a way without changing the values in data.table -

plot_ly(data, x = ~week, y = ~price, color= ~replace(promotion, is.na(promotion), "NA"))

enter image description here

Upvotes: 2

Pork Chop
Pork Chop

Reputation: 29417

library(plotly)
options(stringsAsFactors = F)
data = data.frame(week=c(1,2,3),price=c(2,2.5,1.5),promotion=c("p1",NA,"p2"))
data$promotion[is.na(data$promotion)] <- "NA"
plot_ly(data, x = ~week, y = ~price,color=~promotion)

Upvotes: 2

Related Questions