簡體   English   中英

在 plotly (R) 中按另一列對條形圖進行分組

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

如何在 plotly 中使用 R 獲得按 State 分組的條形圖?

我想要的結果應該像這個在 excel 中制作的示例圖表:單擊此處查看圖像

我的數據:

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
  )
)

我的代碼:

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

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 解決方案

並且,使用ggplotly

ggplotly()

在此處輸入圖片說明

一個純粹的情節解決方案可能看起來像這樣。 對於不同的子類別,您必須使用子圖:

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