R中具有多个变量的简单条形图-类似于Excel [英] Simple bar plot with multiple variables in R - Similar to Excel
本文介绍了R中具有多个变量的简单条形图-类似于Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数据框:
Unit <- c(A, B, C, D)
Yes <- c(50, 65, 20, 41)
No <- c(70, 67, 40, 20)
Missing <- c(10, 12, 8, 7)
df <- data.frame(Unit, Yes, No, Missing)
我想在Excel中使用简单的条形图(请参见附件图): Excel情节
I want to use simple bar plot such as in Excel (Please see attached plot):Excel Plot
https://i.stack.imgur.com/BvWSA.jpg
我使用了ggplot,但仅用于一个Var,如果添加其他变量,则会给我错误:
I used ggplot but only for one Var, If I add others it gave me error:
ggplot(data = df, aes(x = Unit, y = Yes)) +
geom_col() +
geom_text(aes(label = Yes), position = position_stack(vjust = 0.5))
谢谢.
推荐答案
您的数据必须采用长格式而不是宽格式,才能以ggplot进行绘制
Your data needs to be in long format, not wide format, to plot in ggplot
Unit <- c("A", "B", "C", "D") #character objects need quotes
Yes <- c(50, 65, 20, 41)
No <- c(70, 67, 40, 20)
Missing <- c(10, 12, 8, 7)
df <- data.frame(Unit, Yes, No, Missing)
require(tidyr)
df.long <- gather(df, variable,value, -Unit)
一旦数据采用长格式,position_dodge()
就会为您提供所需的图形
Once the data is in long format, position_dodge()
will give you the graph you want
ggplot(data = df.long, aes(x = Unit, y = value, fill = variable)) +
geom_col(position = position_dodge())
这篇关于R中具有多个变量的简单条形图-类似于Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文