具有单个分类变量和多个离散/连续变量的条形图

时间:2020-07-06 14:28:30

标签: r ggplot2

我有如下汇总数据

实验室名称良好测试不良测试总计测试 1主1683 91 1774 2区1200 2569 2769 3区2 106 1898 2004 4区3 53 808 861 5区4 115 1241 1356 6 District5 NA NA 0

我正在尝试从Excel绘制类似于该图表的图表

[![Barchat] [2]] [2]

[2]: https://i.stack.imgur.com/f7DyF.png

我使用了以下脚本,但未成功

tidy_Data = df %>% 
  gather(key, value, Bad_tests, Good_tests)
tidy_Data
ggplot(aes(value)) + 
geom_density(aes(fill = key), show.legend = FALSE) + `
facet_grid(vars(Lab_Name), vars(key), scales = "free")

请帮助

2 个答案:

答案 0 :(得分:1)

下一个代码将帮助您达到类似的目的:

library(tidyverse)
#Data
Data <- data.frame(LabName=c('Main',paste0('District',1:5)),
                   Good_tests=c(1683,200,106,53,115,0),
                   Bad_tests=c(91,2569,1898,808,1241,0),stringsAsFactors = F)
#Variables
Data$Total_tests <- Data$Good_tests+Data$Bad_tests

#Tidy and Plot
tidy_Data = Data %>% 
  gather(key, value, Bad_tests, Good_tests,Total_tests)

ggplot(tidy_Data,aes(x=LabName,y=value,fill=key)) + 
  geom_bar(stat = 'identity',position = position_dodge())

enter image description here

答案 1 :(得分:1)

library(dplyr)
library(tidyr) # pivot_longer
library(ggplot2)
tibble(lab = c("m", "d1", "d2"), gt = c(1683, 200, 106), bt = c(91, 2569, 1898)) %>%
  mutate(lab = paste(lab, gt, bt, sep = "\n")) %>%
  pivot_longer(-lab) %>%
  ggplot(aes(lab, value, fill = name, group = name)) +
  geom_col(position="dodge") +
  xlab(NULL) +
  theme(legend.position = "bottom")

enter image description here