我正在使用ggplot绘制以下数据:
df<- data.frame(name= c("g1","g1","p1","p1"),fc = c(-1.32,-2.11,-1.17,-3.23),fdr = c(.0001,.0001,.07,.0002),cond= c("2v1","3v1","2v1","3v1"))
head(df)
name fc fdr cond
g1 -1.32 .0001 2v1
g1 -2.11 .0001 3v1
p1 -1.17 .07 2v1
p1 -3.23 .0002 3v1
使用ggplot代码:
df$name<- as.factor(df$name)
df$name <- relevel(df$name, as.character(df$name[3]))
ggplot(df, aes(name,fc), group=variable)+
geom_col(aes(fill=factor(as.numeric(fdr)<0.05)), width = 0.98,color="white")+
coord_flip()+scale_fill_manual(values = c("FALSE"= "#00BFC4","TRUE"= "#F8766D"))+
geom_hline(yintercept = 0, colour = "gray" )+
geom_text(aes(label=round(fc,2)),angle = 90, position = position_stack(vjust = 0.5), size =3.5, color= "white")
p1的图表似乎被翻转,其中-1.17的栏位于顶部,而标签仍位于底部。我希望灰色的条形图位于底部,标签为&#34; 1.17&#34;在它的中间。 我将不胜感激任何帮助。谢谢
答案 0 :(得分:1)
我建议尽可能多地在data.frame
中设置绘图特征。这将有助于将aes从一层保持到另一层。
library(ggplot2)
library(dplyr)
df <- data.frame(name = c( "g1", "g1", "p1", "p1"),
fc = c(-1.32, -2.11, -1.17, -3.23),
fdr = c(.0001, .0001, .07, .0002),
cond = c("2v1", "3v1", "2v1", "3v1"))
# use dplyr to set the name and fill factors
# use the group_by to generate the cumsum for defining where the label should be
# located.
df <-
df %>%
dplyr::mutate(name = factor(name, levels = c("p1", "g1")),
fill = factor(fdr < 0.05, c(TRUE, FALSE), c("fdr < 0.05", "fdr >= 0.05"))) %>%
dplyr::group_by(name) %>%
dplyr::mutate(text_y = -cumsum(-fc)) %>%
dplyr::ungroup()
# the plot
ggplot(df) +
aes(x = name, y = fc, fill = fill) +
geom_col(width = 0.98, color="white") +
coord_flip() +
geom_hline(yintercept = 0, colour = "gray" ) +
geom_text(mapping = aes(y = text_y, label = round(fc, 2)),
angle = 90,
color = "white",
position = position_stack(vjust = 0.5),
size = 3.5,
color = "white")