首页 > 解决方案 > 在基本函数 barplot() 中自定义 Barplot

问题描述

我有一个日期框架(df),有 2 列:一个数字和一个 as.factor(),三个级别:

我想制作一个 barplot() ,每个因素都为其各自的组着色(简单),并更改绘图的顺序,使每个因素彼此相邻出现(这是我卡住的地方)。

我遵循与 boxplot() 相同的逻辑,但它的工作方式似乎不同。我还尝试了以下几个 stackoverflow 线程的示例,包括(但不限于)这个:

但仍然无法让它工作。

这是我尝试过的,它与 boxplot 函数配合得很好:

df <- read.table("https://pastebin.com/raw/zaETq28M", header = T)

df$Treatment <- as.factor(df$Treatment)

levels(df$Treatment) # note: I would like to display order to be: Pre, Post, then Blank.

df$Treatment <- ordered(df$Treatment, levels = c("Pre","Post","Blank")) # set to the right order

barplot(df$Cq,names.arg = df$Treatment ,col = df$Treatment, ylim=c(0,30), main = "Not the right order bar plot", cex.main=2)

总的来说,我应该有 66 个单独的条(我这样做),但不知何故,图表的顺序不是我设置的,并且组仍然分开。我怎样才能简单地获得 3 个不同的组?含义,首先显示所有“Pre”,然后所有“post”,然后是“blank”

未来职位的一般问题:

  1. 当我发布问题时,如何让我的图表显示在 Stackoverflow 上?出于某种原因,我的帖子从不包含我的图表。
  2. 此外,任何关于使用色盲托盘的建议都会很棒,但如果需要,我可以手动执行此操作。只是好奇是否有一种自动的方法,所以我不需要在我的所有图表中手动设置它

感谢您的帮助

标签: rplot

解决方案


你是这个意思吗?首先是Pre,然后是Post ,然后是空白。每个组内的顺序都被保留。图例添加了空白== No Treatment

df <- read.table("https://pastebin.com/raw/zaETq28M", header = T)

df_Pre <- df[which(df$Treatment == 'Pre'),]
df_Post <- df[which(df$Treatment == 'Post'),]
df_Blank <- df[which(df$Treatment == 'Blank'),]
ddf <- rbind(df_Pre, df_Post, df_Blank)
ddf$color <- c(rep('blue', nrow(df_Pre)), rep('red', nrow(df_Post)), rep('magenta', nrow(df_Blank)))
barplot(ddf$Cq, col = ddf$color, names = rownames(ddf))
legend("bottomleft", 
       legend = c("Pre-Treatmen", "Post-Treatment", 'No Treatment'), 
       fill = c("darkblue", "red","magenta"))


推荐阅读