Search code examples
rplotly

Plotting plots in same colors


I working with plotly in R. I am trying to plot charts with the same colors. Below you can see data and charts.

library(plotly)
library(reshape2)
library(dplyr)

df<-data.frame(city=c("NYC","Seattle","Boston","LA","Seattle"),
               value=c(100,200,300,400,500))
df <-melt(df)

Now I am plotting pie chart with colors shown below:

fig<-df %>% 
  plot_ly(labels = ~city, values = ~value)
fig <- fig %>% add_pie(hole = 0.6)
fig

enter image description here

Finally, I want to plot a bar chart with the same colors as the pie plot, shown above. In order to do this, I tried this command lines :

df <-melt(df)
fig <- plot_ly(df, x = ~city, y = ~value, type = 'bar')
fig

enter image description here

So can anybody help me with how to plot a barplot with the same colors as pie chart ?


Solution

  • Here's a somewhat hacky but effective solution:

    fig <- ggplot(df, aes(city, value, fill = city)) + 
           geom_col() +
           scale_fill_manual(values = c("#2ca02c", "#ff7f0e", 
                                        "#d62728", "#1f77b4")) +
           theme_minimal() +
           theme(panel.grid.major.x = element_blank())
    
    ggplotly(fig)
    

    enter image description here