如何从2D数据框中创建ggplot2条形图?

时间:2020-02-16 20:31:26

标签: r ggplot2

我有一个由R中的矩阵数据类型创建的2d数据帧,在垂直和水平侧均具有标签。

如何在ggplot的aes()标记中引用它们以绘制条形图?

我呼吁在X栏中添加所有列(Up1-5),并将垂直标签添加为图例。

数据框:

            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

代码:

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

1 个答案:

答案 0 :(得分:1)

您需要将数据帧转换为长格式。这是使用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")

数据

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