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
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
So can anybody help me with how to plot a barplot with the same colors as pie chart ?
CodePudding user response:
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)
CodePudding user response:
Pie Chart:
PieChart <- df %>% plot_ly(labels = ~city, values = ~value,
marker = list(colors = cols), showlegend = TRUE) %>%
add_pie(hole = 0.6)
PieChart
Note that this would still give you different colours for the cities, so another suggestion that I have besides the linked answer above is to try creating a new data frame that has the unique four cities i.e no repetition, the summation of the values for the repeated cities, and bind another column that has a unique colour per city.
CodePudding user response:
You may use ggplot2
package for both charts and it shall give matching colours to the city
in each chart:
#install.packages('ggplot2')
library(ggplot2)
library(dplyr)
#your data frame
df<-data.frame(city=c("NYC","Seattle","Boston","LA","Seattle"),
value=c(100,200,300,400,500))
df <-melt(df)
PieChart <- df %>% ggplot(aes(x="", y=value, fill=city))
geom_bar(stat = "identity", width=1)
coord_polar("y",start=0)
theme_void()
PieChart
BarChart <- df %>% ggplot(aes(x=city, y=value, fill=city))
geom_bar(stat = "identity")
theme_void()
xlab("City") ylab("Value")
BarChart