水平 geom_bar,无重叠、条宽相等和自定义轴刻度标签

Horizontal geom_bar with no overlaps, equal bar widths, and customized axis tick labels

可能是一个简单的 ggplot2 问题。

我有一个 data.frame 和一个 numeric 值、一个分类 (factor) 值和一个 character 值:

library(dplyr)
set.seed(1)
df <- data.frame(log10.p.value=c(-2.5,-2.5,-2.5,-2.39,-2,-1.85,-1.6,-1.3,-1.3,-1),
                 direction=sample(c("up","down"),10,replace = T),
                 label=paste0("label",1:10),stringsAsFactors = F) %>% dplyr::arrange(log10.p.value)
df$direction <- factor(df$direction,levels=c("up","down"))

我想使用 geom_bar 将这些数据绘制为 barplot,其中条形是水平的,它们的长度由 df$log10.p.value 决定,它们的颜色由 df$direction 决定,y-axis tick 标签为 df$label,其中条形按 df$log10.p.value.

垂直排序

如您所见,df$log10.p.value 不是唯一的,因此:

ggplot(df,aes(log10.p.value))+geom_bar(aes(fill=direction))+theme_minimal()+coord_flip()+ylab("log10(p-value)")+xlab("")

给我:

我如何:

  1. 使条形不相互重叠。
  2. 具有相同的宽度。
  3. 差一点?
  4. y-axis tick 标签是否为 df$label

谢谢

这是一种可能的解决方案。请注意,默认情况下,geom_bar 使用 frequency/count 确定柱的长度。因此,您需要为值映射指定stat = "identity"

# since all of your values are negative the graph is on the left side
ggplot(df, aes(x = label, y = log10.p.value, fill = direction)) +
  geom_bar(stat = "identity") +
  theme_minimal() +
  coord_flip() + 
  ylab("log10(p-value)") +
  xlab("")