图表(R)中的另一列组条形图

时间:2017-05-31 15:44:45

标签: r plotly

如何使用R在图表中按状态对此图表进行分组?

数据:

  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)

以excel制作的示例图表: Click here for image

    plot_ly() %>%
      add_trace(
        x = ~City,
        y = ~Population,
        type = 'bar',
        name = 'Population')

2 个答案:

答案 0 :(得分:0)

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

并使用ggplotly

ggplotly()

enter image description here

答案 1 :(得分:0)

一个纯粹的绘图解决方案可能看起来像这样。对于不同的子类别,您必须使用子图:

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)

enter image description here