Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group bar chart by another column in plotly (R)

Tags:

r

plotly

How can I get a bar chart grouped by State using R in plotly?

My desired result should like this sample chart made in excel: Click here for image

My data:

data <- data.frame(
  State = c(
    "Tennessee", "Tennessee", "Tennessee", "Tennessee",
    "Kentucky", "Kentucky", "Kentucky", "Kentucky", "Kentucky",
    "Georgia", "Georgia", "Georgia"
  ),
  City = c(
    "Chattanooga", "Knoxville", "Memphis", "Nashville",
    "Covington", "Owensboro", "Bowling Green", "Lexington", "Louisville",
    "Columbus City", "Augusta", "Atlanta City"
  ),
  Population = c(
    177571, 186239, 652717, 660388,
    40640, 57265, 58067, 295803, 597337,
    189885, 195844, 420033
  )
)

My code:

plot_ly(data) %>%
  add_trace(
    x = ~City,
    y = ~Population,
    type = 'bar',
    name = 'Population')
like image 623
Xenedra Avatar asked Nov 01 '25 00:11

Xenedra


1 Answers

In ggplot:

data <- data.frame(State, City, Population)
colnames(data)<-c("category","subcategory","population")

ggplot(data, aes(category, population)) +   
  geom_bar(aes(fill = category, color=subcategory), position = "dodge", stat="identity")+
  theme_minimal() +
  scale_color_manual(values=c(rep("white", 17))) +
  theme(legend.position="none") 

ggplot2 solution

and, using ggplotly:

ggplotly()

enter image description here

like image 65
shosaco Avatar answered Nov 03 '25 16:11

shosaco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!