簡體   English   中英

R - 帶圖例的分組條形圖

[英]R - Grouped Barplot with legend

我試圖將其他答案中的代碼/指南復制到分組條形圖幫助中,但似乎總是遇到錯誤消息。 我什至在嘗試添加標題/圖例之前就得到了這些。

我有以下數據集;

CT報告終端 ATM 數據庫終端 會員統計終端 HC 錯誤
11月21日 406 139 1251 888
12月21日 640 1438 1544 740
1月22日 795 939 1000 297

我想復制下圖;

在此處輸入圖像描述

我可以在 excel 中輕松完成此操作,但嘗試堅持使用 R。我有以下代碼;

library(ggplot2)

read_excel("ct_summary.xlsx")

data <- read_excel("ct_summary.xlsx")

Category <- c("CT Report Terminals", "ATM DB Terminals", 
              "Member Stats Terminals", "HC Errors")

ggplot(data, aes(x = Category, y = Category, fill=Month)) +
  geom_bar(stat="identity", position = "dodge")

錯誤消息Error: Aesthetics must be either length 1 or the same as the data (3): x and fill keeps appearing or I get errors around bar height.

您需要將您的數據 pivot 轉換成長格式。 您可以使用tidyr::pivot_longer(data, -1)輕松完成此操作。 以下代碼中的所有其他內容都只是為了使您的 plot 看起來更像原來的外觀調整:

library(ggplot2)
library(dplyr)
library(tidyr)

data %>% 
  pivot_longer(-1) %>%
  mutate(Month = factor(Month, c("Nov-21", "Dec-21", "Jan-22")),
         name = stringr::str_wrap(name, 12),
         name = factor(name, levels(factor(name))[c(2, 1, 4, 3)])) %>%
  ggplot(aes(name, value, fill = Month)) +
  geom_col(width = 0.6, position = position_dodge(width = 0.8)) +
  scale_fill_manual(values = c("#4472c4", "#ed7d31", "#a5a5a5")) +
  scale_y_continuous(breaks = 0:9 * 200) +
  labs(x = "", y = "", title = "Heading TBC") +
  theme_bw() +
  theme(panel.grid.major.x = element_blank(),
        panel.border = element_blank(),
        plot.title = element_text(hjust = 0.5))

在此處輸入圖像描述


數據

data <- structure(list(Month = c("Nov-21", "Dec-21", "Jan-22"), 
                       `CT Report Terminals` = c(406L, 640L, 795L), 
                       `ATM DB Terminals` = c(139L, 1438L, 939L), 
                       `Member Stats Terminals` = c(1251L, 1544L, 1000L), 
                       `HC Errors` = c(888L, 740L, 297L)), 
                  class = "data.frame", row.names = c(NA, -3L))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM