[英]R: Stacked bar plot with barpot, ggplot or plotly
I've been searching to find a solution, but none of the already existing questions fit my problem. 我一直在寻找解决方案,但是没有一个已经存在的问题适合我的问题。
I have a data.frame: 我有一个data.frame:
Pat <- c(1,1,1,1,1,1,2,2,2,2,2,2)
V_ID <- c(1,1,6,6,9,9,1,1,6,6,9,9)
T_ID <- c("A","B","A","B","A","B","A","B","A","B", "A","B")
apples <- c(1,1,1,1,1,1,1,1,1,1,1,1)
bananas <- c(2,2,2,2,2,2,2,2,2,2,2,2)
cranberries <- c(3,3,3,3,3,3,3,3,3,3,3,3)
df <- data.frame(Pat,V_ID, T_ID, apples, bananas, cranberries)
I am trying to plot: 我正在尝试绘制:
barplot(as.matrix(df[,4:6]) ,
main="tobefound", horiz = FALSE,width = 1,
names.arg=colnames(df[,4:6]),
las=2,
col = c("blue", "red"),
legend = df[,3],
args.legend = list(x="topleft"),
beside= FALSE)
BARPLOT BARPLOT
I need two changes: First of all I like to have all "B"s (so the red part in every stack) piled up together and then the blue ones on top. 我需要进行两项更改:首先,我希望将所有的“ B”(因此,每个堆栈中的红色部分)堆积在一起,然后将蓝色的顶部堆叠在一起。 Second: is there a way of decreasing the legend to only A and B once besides addressing this via
第二:除了通过以下方式解决此问题外,是否还有一种方法可以将图例仅减少到A和B
legend = df[1:2,3],
I am also looking for a solution using plotly or ggplot. 我也在寻找使用plotly或ggplot的解决方案。
Thanks, 谢谢,
Using base graphics, you needed to sort df
by T_ID
first. 使用基本图形,您需要首先按
T_ID
对df
进行排序。
df = df[order(df$T_ID), ]
barplot(as.matrix(df[,4:6]) ,
main="tobefound", horiz = FALSE,width = 1,
names.arg=colnames(df[,4:6]),
las=2,
ylim = c(0,40),
col = 1+as.numeric(as.factor(df$T_ID)),
border = NA,
beside= FALSE)
box()
legend('topleft', fill = 1+as.numeric(as.factor(levels(df$T_ID))), legend = levels(as.factor(df$T_ID)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.