【问题标题】:Customize Barplot in base function barplot()在基本函数 barplot() 中自定义 Barplot
【发布时间】:2021-01-07 10:42:49
【问题描述】:

我有一个日期框架 (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. 此外,任何关于使用色盲托盘的建议都很好,但如果需要,我可以手动执行此操作。只是好奇是否有自动的方法,所以我不需要在我的所有图表中手动设置它

感谢您的帮助

【问题讨论】:

    标签: r plot


    【解决方案1】:

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

    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"))
    

    【讨论】:

    • 嗨。谢谢你的时间。不,这是我组的频率分布表。我的 y 轴应该是变量“cq”,x 轴应该有 3 个组:Pre、Post 和 Blank 如果你运行代码```table(df$Treatment),你会看到我有 66总数据点,意味着 66 个单独的条形图。这有帮助吗?尝试按原样运行我的代码,您会明白我的意思,只是分组错误
    • 我更新了我的问题,希望能澄清我的观点
    • @Andy,我希望我现在明白了——请看新的编辑。
    • 是不是很酷!非常感谢您花时间在这方面:)
    • 试试这个barplot(ddf$Cq, col = ddf$color, names = rownames(ddf), axis.lty = 1, names.arg = rep('', nrow(ddf)))
    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 2022-08-03
    • 2021-09-03
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    相关资源
    最近更新 更多