使用 ggplot2 将条形图组合在一起

Group bar plots together using ggplot2

我的数据如下:

Accounts Income Expense Benefit
selling food 338.96 43.18 295.78
selling books 2757.70 2341.66 416.04
selling bikes 1369.00 1157.00 212.00

我想得到这样的组合条形图:

为此,我编写了这个 R 脚本:

## Take a data set in and produces a bar chart

## Get rid of the column containing account names to only keep values:
values <- as.matrix(data)[,-1]

## Convert strings to numbers:
values <- apply(values, 2, as.numeric)

## Transpose the matrix:
values <- t(values)

## Vertical axis labels are taken from the first column:
accountNames <- data$Accounts

## The legend is the first row except the first cell:
legend <- tail(names(data), -1)

## Colors are taken randomly
colors <- rainbow(length(legend))

## Increase left margin to fit horizontal axis labels:
par(mar=c(5,8,4,2)+.1)

## Axis labels are drawn horizontal:
par(las=1)

barplot(
  values,
  names.arg=accountNames,
  col=colors,
  beside = TRUE,
  legend = legend,
  horiz = TRUE
)

我想用 ggplot2 使这个条形图现代化,我将它用于同一文档的其他图表。我发现要执行的文档总是假设数据的形状非常不同,而且我对 R 的了解还不足以找出自己该怎么做。

这是基本的,然后你可以按照你想要的方式自定义情节

图书馆

library(tidyverse)

数据

data <-
tibble::tribble(
        ~Accounts, ~Income, ~Expense, ~Benefit,
   "selling food",  338.96,    43.18,   295.78,
  "selling books",  2757.7,  2341.66,   416.04,
  "selling bikes",    1369,     1157,      212
  )

代码

data %>%
  #Pivot Income, Expense and Benefit
  pivot_longer(cols = -Accounts) %>% 
  #Define each aesthetic
  ggplot(aes(x = value, y = Accounts, fill = name))+
  # Add geometry column 
  geom_col(position = position_dodge())

结果

1.Bring 您的长格式数据 pivot_longer

2.Then 用 geom_bar

绘图
  1. 使用coord_flip
library(tidyverse)
df %>% 
    pivot_longer(
        cols= -Accounts,
        names_to = "Category",
        values_to = "values"
    ) %>% 
    ggplot(aes(Accounts, y=values, fill = Category)) +
    geom_bar(stat="identity", position = "dodge")+
    coord_flip() +
    theme_classic()