ggplot - 来自同一数据框的两个变量的柱状图 [英] ggplot - bar plot for two variable from the same data frame

查看:1969
本文介绍了ggplot - 来自同一数据框的两个变量的柱状图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我可以创建一个像下面这样的变量的列图

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

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



解决方案使用 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(ST at ='identity',position ='dodge')


I need to generate a plot with bar graph for two variables.

I can create a column graph for one variable like below

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

how to go about getting a chart like below ( created in excel) - essentially I need add bar plot of more than one variable.

解决方案

With ggplot you need to convert data to long format so that one column defines the color and one column defines the y value:

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')

这篇关于ggplot - 来自同一数据框的两个变量的柱状图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆