我正在尝试制作堆积条形图,但它根本不起作用。我已附上我的数据和我尝试过的脚本。我的数据是制表符分隔的,只有 4 行数据。颜色应该是我可以为条形图着色的一种方法。
Person Count Color
Jim 35 Y
Jim 10 N
Jenny 12 Y
Jenny 25 N
所以我期待的是吉姆的金条彼此堆叠在一起,并且让珍妮的下一个金条也堆叠起来。但事实并非如此,酒吧虽然存在,但彼此相邻,尽管属于同一个人。
我尝试过的代码
barplot(count, col = color) ##this will get me the unstacked bars
###what I have seen as examples but I already have a table...
count = table (person, count)
count
barplot(count, col = color)
最佳答案
barplot 函数(来自图形包)需要描述构成绘图的条形的向量或值矩阵。不是数据框。因此,如果您的数据结构如下:
> X <- matrix(c(12,25,35,10), nr=2)
> dimnames(X) <- list(Color=c("Y","N"), Person=c("Jenny","Jim"))
> X
Person
Color Jenny Jim
Y 12 35
N 25 10
这是一个 2x2 的计数表,那么您可以轻松绘制它:
> barplot(X)
当然,R 通常会提供最少的输出,包括图形,因此为了使其看起来更美观,您需要添加一些参数。
op <- par(mar=par("mar") + c(0,0,0,1)) # add some space for the legend on the right, saving the original pars
barplot(X, xlab="Person", ylab="Count", # add axis labels
las=1, # make tick labels horizontal
col=c("turquoise2","tomato"), border="white", # change colors
legend=TRUE, # add a legend with some parameters...
args.legend=list(x="right", title="Color", bt="n", border="white", inset=-0.2)
)
par(op) # restore original graphical parameters
结果类似于 ggplot 生成的默认图表,它需要数据框,而不是矩阵。
关于r - 返回单个条形的堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60235546/