我一直在寻找解决方案,但现有的问题都不适合我的问题。
我有一个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)
我想绘图:
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
我需要两个改变: 首先,我喜欢将所有“B”(所有每个堆叠中的红色部分)堆叠在一起,然后将蓝色部分堆叠在一起。第二:除了通过
解决此问题之外,还有一种方法可以将图例减少到只有A和B一次legend = df[1:2,3],
我也在寻找使用plotly或ggplot的解决方案。
谢谢,
答案 0 :(得分:3)
首先重塑:
df_long <- tidyr::gather(df, 'key', 'value', apples:cranberries)
然后绘制:
ggplot(df_long, aes(key, value, fill = T_ID)) + geom_col(col = 'black')
或许没有边界:
ggplot(df_long, aes(key, value, fill = T_ID)) + geom_col()
答案 1 :(得分:3)
使用基本图形,您需要先df
按T_ID
排序。
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)))