petermark
petermark

Reputation: 85

Change color of bar plots

I have a plot:

p <- plot_ly(
  x = c(data$sum),
  y = c(data$candidate),
  name = "Trump v Clinton",
  type = "bar"
)

Candidate is realDonaldTrump and HilaryClinton while sum is 10000 and 5000.

Is it possible to set the colour for the bar of each candidate? I.e. Trump be red and Hilary blue.

Upvotes: 0

Views: 1952

Answers (2)

Dave2e
Dave2e

Reputation: 24079

Looking for something like this?:

library(plotly)

data<-data.frame(sum=c(10000, 5000), candidate=c("DonaldTrump", "HilaryClinton"))
data$color<-c("red", "blue")

p <- plot_ly(
  y = data$sum,
  x = data$candidate,
  color = I(data$color),
  type = "bar"
)
p<-layout(p, title = "Trump vs Clinton")
print(p)

It plot as a vertical barplot, I needed to swap the values for the x and y axis.

Upvotes: 2

Sandipan Dey
Sandipan Dey

Reputation: 23101

This should also work:

library(plotly)
data.frame(sum=c(10000, 5000), candidate=c("DonaldTrump", "HilaryClinton")) %>% 
  plot_ly(x = candidate, y = sum, type = "bar", color = candidate)

enter image description here

Upvotes: 0

Related Questions