简体   繁体   English

在 plotly (R) 中按另一列对条形图进行分组

[英]Group bar chart by another column in plotly (R)

How can I get a bar chart grouped by State using R in plotly?如何在 plotly 中使用 R 获得按 State 分组的条形图?

My desired result should like this sample chart made in excel:我想要的结果应该像这个在 excel 中制作的示例图表:单击此处查看图像

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() %>%
  add_trace(
    x = ~City,
    y = ~Population,
    type = 'bar',
    name = 'Population')

In ggplot :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 解决方案

and, using ggplotly :并且,使用ggplotly

ggplotly()

在此处输入图片说明

A pure plotly solution may look like so.一个纯粹的情节解决方案可能看起来像这样。 With different subcatgories you have to use subplots:对于不同的子类别,您必须使用子图:

data %>% 
  mutate(State = factor(State, levels = c("Tennessee", "Kentucky", "Georgia"))) %>% 
  split(.$State) %>% 
  purrr::imap(function(x, y) {
    mutate(x, City = reorder(City, Population)) %>% 
      plot_ly() %>%
      add_bars(x = ~City,
               y = ~Population,
               color = ~State,
               colors = c(Tennessee = '#1f77b4',  # muted blue
                          Kentucky = '#ff7f0e',  # safety orange
                          Georgia = '#2ca02c'  # cooked asparagus green"
               )) %>% 
      layout(xaxis = list(tickvals = (nrow(x) -1) / 2, ticktext = y))}
    ) %>%
  subplot(shareY = TRUE)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM