ggplot - 来自同一数据框的两个变量的条形图

问题描述 投票:0回答:1

我需要为两个变量生成带条形图的图。

我可以为下面的一个变量创建一个列图

df <- head(mtcars)
df$car <- row.names(df)
ggplot(df) + geom_col(aes(x=car, y=disp))

如何获得如下图表(在excel中创建) - 基本上我需要添加多个变量的条形图。

enter image description here

r ggplot2
1个回答
1
投票

使用ggplot,您需要将数据转换为长格式,以便一列定义颜色,一列定义y值:

library(tidyr)
df$car = row.names(df)
df_long = gather(df, key = var, value = value, disp, hp)
ggplot(df_long, aes(x = car, y = value, fill = var)) +
  geom_bar(stat = 'identity', position = 'dodge')

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.