我刚刚从Excel来到R,并对ggplot2的图表质量的优雅感到非常兴奋。由于它们是不同的工具,因此有不同的做事方式。我必须训练我的大脑以R(ggplot2)的方式思考。
我想知道,如何在ggplot2中绘制多列数据。我想以下面的数据为例:
State Quarter 1 Quarter 2 Quarter 3 Total
Connecticut 385 410 521 1,316
Pennsylvania 545 416 598 1,559
Delaware 506 515 731 1,752
New Jersey 591 781 617 1,989
Maryland 946 436 895 2,277
Vermont 945 816 895 2,656
New York 910 867 946 2,723
Total 4,828 4,241 5,203 14,272
问题:
答案 0 :(得分:1)
df <- read.csv(text="State,Quarter1,Quarter2,Quarter3,Total
Connecticut,385, 410, 521, 1316
Pennsylvania, 545, 416, 598, 1559
Delaware,506, 515, 731, 1752
New Jersey,591, 781, 617, 1989
Maryland,946, 436, 895, 2277
Vermont, 945, 816, 895, 2656
New York,910, 867, 946, 2723
", header=T)
library(reshape2)
df <- melt(df, variable.name="Quarter")
library(ggplot2)
ggplot(df[df$Quarter != "Total",]) +
geom_bar(aes(State, value, fill = Quarter), stat="identity")
这会创建以下图表:
答案 1 :(得分:1)
根据评论中的建议,首先melt
数据框:
require(reshape2)
require(ggplot2)
data = read.table(text="
State, Quarter1, Quarter2, Quarter3, Total
Connecticut, 385, 410, 521, 1316
Pennsylvania, 545, 416, 598, 1559
Delaware, 506, 515, 731, 1752
New Jersey, 591, 781, 617, 1989
Maryland, 946, 436, 895, 2277
Vermont, 945, 816, 895, 2656
New York, 910, 867, 946, 2723
Total, 4828, 4241, 5203, 14272",header=T,sep=',')
data.new <- melt(head(data,-1))
现在是堆积条形图:
ggplot(head(data.new,-1), aes(State,value,fill=variable)) + geom_bar(position="dodge")
对于并排条形图:
ggplot(head(data.new,-1), aes(State,value,fill=variable)) + geom_bar()