简体   繁体   中英

Grouped Bar Plot Extra Variable in R

I have the following data frame in R:

> data <- data.frame(tbi_military[0:4])
> data
          Severity Active Guard Reserve
1      Penetrating    189    33      12
2           Severe    102    26      11
3         Moderate    709   177      63
4             Mild   5896  1332     541
5 Not Classifiable    122    29      12

And when I do barplot(as.matrix(data)) I get the following output:

Barplot Image

Is there a way for me to get rid of the severity on the x-axis to only have Active, Guard, Reserve? Thanks

one option is to send only the data you want to plot to the plotting function. In this case you want all columns from the second to the last (number four) so a small adjustment to your function call does the job:

barplot(as.matrix(data[, 2:4]))

在此处输入图像描述

A solution within the tidyverse (dplyr, tidyr and ggplot2) would be this:

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

data %>% 
  # get data in tidy format to be able to use ggplot2 efciently
  tidyr::pivot_longer(-Severity, names_to = "Type", values_to = "Value") %>% 
  # set up the plot by assigning variable to plot
  ggplot2::ggplot(aes(Type, Value, fill = Severity)) +
  # put out a bar chart with stat parameter set for stacked barchart
  ggplot2::geom_bar(stat = "identity")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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