在 R 中绘制分组条形图 [英] plotting grouped bar charts in R
问题描述
我正在尝试在 R 中绘制此数据 -
i am trying to plot this data in R -
column1 column2 column3
1-2 abc 10
1-2 def 15
1-2 ghi 20
2-3 abc 80
2-3 def 95
2-3 ghi 10
3-4 abc 30
3-4 def 55
3-4 ghi 80
x 轴将是 column1(因此 1-2、2-3 和 3-4 将作为 x 轴出现),并且在 y 轴上,应为每个 column2 元素绘制 column3 中的值.所以这本质上是一个分组"条形图.
the x axis would be column1 (so 1-2, 2-3 and 3-4 would be present as the x axis), and on y axis, the values in column3 should be plotted for each of the column2 elements. So this would be a "grouped" barchart essentially.
我无法使用 R 绘制此分组条形图.我使用的代码片段如下:
I am not able to plot this grouped bar chart using R. The code snippet I am using is below:
dataset <- fetch(rs,n=-1)
plot_var <- table(dataset$percentage, dataset$age)
barplot(plot_var, names.arg,
main="Title of Graph",
xlab="Column1", col=c("darkblue","red"),
legend = rownames(plot_var), beside=TRUE)
如何显示此分组条形图?谢谢!
How do I get this grouped bar chart to display? Thanks!
推荐答案
您的问题似乎归结为错误的数据格式.您需要使用正确的行名称结构制作一个矩阵,以使用基本图形创建您想要的绘图.这是您的解决方案:
Your problem seem to come down to wrong data formatting. You need to make a matrix with the right row names structure to create plot that you want with base graphics. Here is your solution:
#your data...
d <- data.frame(row.names=c("1-2","2-3","3-4"), abc = c(10,80, 30),
def = c(15, 95, 55), ghi = c(20, 10, 80))
#but you make a matrix out of it to create bar chart
d <- do.call(rbind, d)
#...and you are sorted
barplot(d, beside = TRUE, ylim=c(0,100), legend.text = rownames(d),
args.legend = list(x = "topleft", bty="n"))
然而,我有时喜欢使用 lattice
来完成这种任务.这一次你甚至不需要制作矩阵,你只需保持你的 data.frame
原始格式:
However, I sometimes like to use lattice
for this kind of task. This time you don't even have to make matrix, you just keep your data.frame
in original format:
d <- data.frame(column1=rep(c("1-2","2-3","3-4"), each=3),
column2=rep(c("abc", "def", "ghi"), 3),
column3=c(10, 15, 20, 80, 95, 10, 30, 55, 80))
require(lattice)
barchart(column3 ~ column1, groups=column2, d, auto.key = list(columns = 3))
这篇关于在 R 中绘制分组条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!