How to create a ggplot2 bar chart out of a 2d data frame?

I have a 2d data frame created by a matrix data type in R, that has labels on both vertical and horizontal side.

How can I refer to them in the aes() tag in ggplot to draw a bar chart?

I appeal to add all columns (Up1-5) in X bar, and add vertical labels as legend.

data frame:

            Up1     Up2     Up3     Up4     Up5

Desktop     45026   99184   93127   1498    1597

Laptop      10451   87969   3546    1285    1251

Tablet      45282   12318   8850    7321    8709

Cell-Phone  54754   28377   10380   6363    9179

Code:

ggplot(mydata, aes(x=???, y=???, fill=???) ) + 
  geom_bar(width = 0.5, stat = "identity")

Upvotes: 1

Views: 531

Answers (1)

www
www

Reputation: 39154

You need to convert the data frame to long format. Here is an example using pivot_longer.

library(tidyverse)

dat2 <- dat %>%
  rownames_to_column() %>%
  pivot_longer(cols = -rowname, names_to = "Up")

ggplot(dat2, aes(x = Up, y = value, fill = rowname)) + 
  geom_bar(width = 0.5, stat = "identity")

DATA

dat <- read.table(text = "        Up1     Up2     Up3     Up4     Up5
Desktop 45026 99184 93127 1498 1597

Laptop 10451 87969 3546 1285 1251

Tablet 45282 12318 8850 7321 8709

'Cell-Phone' 54754 28377 10380 6363 9179",
                  stringsAsFactors = FALSE, header = TRUE)

enter image description here

Upvotes: 1

Related Questions