我正在尝试用R创建分组条形图。我尝试使用以下代码创建一个简单的条形图。
x=c(99,9,104,67,86,53,83,29,127,31,179,86,74,80,100,150,68,18,81,47)
names(x)= c("A","C","E","D","G","F","I","H","K","M","L","N","Q","P","S","R","T","W","V","Y")
barplot(x)
y= c(105673,18140,92426,76776,93974,53470,75155,30700,77847,28863,124602,55703,
50160,60685,78693,69581,70846,18285,92789,45728)
names(y)= c("A","C","E","D","G","F","I","H","K","M","L","N","Q","P","S","R","T","W","V","Y")
barplot(y)
我必须结合上面两个条形图。我无法弄清楚如何将它们结合起来。
我尝试使用gplot。
require(ggplot2)
data(mydata)
head(mydata)
ggplot(mydata, aes(aminoacid, fill=cut)) + geom_bar(position="dodge") +
opts(title="aminoacid analysis ")
Error in data.frame(x = c(2L, 3L, 5L, 4L, 7L, 6L, 9L, 8L, 10L, 12L, 11L, :
arguments imply differing number of rows: 21, 228
我也试过以下代码。
counts <- table(mydata)
barplot(counts, main="amino acid analysis",`xlab="aminoacid codes", col=c("darkblue","red")`legend = rownames(counts), beside=TRUE))
Error in barplot.default(counts, main = "aminoacid analysis", :
'height' must be a vector or a matrix
如何解决这些错误?
请帮我创建一个带R的分组条形图。
答案 0 :(得分:15)
欢迎来到SO。
您可能希望查看ggplot2
,在Hadley's page上,您会找到有关如何执行此操作的详细示例。这是一个例子:
# if you haven't installed ggplot, if yes leave this line out
install.packages("ggplot2") # choose your favorite mirror
require(ggplot2)
data(diamonds)
# check the dataset
head(diamonds)
# plot it
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge") +
opts(title="Examplary Grouped Barplot")
ggplot2
包的好处在于您可以轻松更改某些参数(美学,美学)的可视化。例如,您可以查看facects
或堆积的条形图,而不是对它们进行分组。此外,它在Hadley的页面上有详细记录。
为了完整起见,这里还有一个非ggplot2
示例@quickR
# Grouped Bar Plot
counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and VS",
xlab="Number of Gears", col=c("darkblue","red"),
legend = rownames(counts), beside=TRUE)